如何连接到一列下的单元格,其中另一列具有特定值?

  • 本文关键字:一列 连接 何连接 单元格 pandas
  • 更新时间 :
  • 英文 :


有没有更简单的方法可以做到这一点?

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

最新更新