首页 > 解决方案 > 如何连接到另一列具有特定值的一列下的单元格?

问题描述

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

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'])

标签: pandas

解决方案


使用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

推荐阅读