有没有更简单的方法可以做到这一点?
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'])
我将使用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
使用np.where
第一个参数作为条件,第二个参数作为条件True
,第三个条件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