Isaac Ng
Isaac Ng

Reputation: 86

How do I concatenate to a cell under one column where another column has a certain value?

Is there a simpler way to do this?

df = pd.DataFrame({'col1': ['a', 'b', 'c'],
                   'col2': ['1', '2', '3'],
                   })

row = df.index[df['col1'] == 'b'][0]

df.at[row, 'col2'] = ' '.join([df.at[row, 'col2'], 'info'])

Upvotes: 0

Views: 35

Answers (2)

BENY
BENY

Reputation: 323226

I will use idxmax

df.col2=df.col2.astype(str)
df.loc[df['col1'].eq('b').idxmax(), 'col2']+=' info'
df
  col1    col2
0    a       1
1    b  2 info
2    c       3

Upvotes: 2

Vishnudev Krishnadas
Vishnudev Krishnadas

Reputation: 10960

Use np.where with first argument as condition, second as what to replace with if condition is True and third when condition is False

>>> condition = df['col1'] == 'b'
>>> df['col2'] = pd.np.where(condition, df['col2'] + ' info', df['col2'])
>>> df
  col1    col2
0    a       1
1    b  2 info
2    c       3

Upvotes: 2

Related Questions