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'])
解决方案
使用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
推荐阅读
- javascript - Ract Native,滚动到屏幕中的特定位置
- javascript - 在反应列中完美居中图像
- javascript - setInterval + React 钩子导致组件内的多次更新
- spring-boot - 有没有办法从在 Websphere 9.0 上运行的 Spring Boot 触发身份验证
- python - 如何使用优化算法找到可能的最佳参数
- python - 数据框中的冗余值用作键,另一列用作值
- html - 引导轮播没有进展
- openstreetmap - OSM 将给定美国县的所有道路作为 shapefile
- mysql - 使用 node.js 和 passport.js 将经过谷歌验证的用户保存到 mysql 数据库中
- java - 如果hashcode()是根据对象的地址创建hashcode,那么两个内容相同的不同对象如何创建相同的hashcode呢?