python-3.x - 麻烦根据python3和pandas中的列值更改csv行
问题描述
如果 columnA 包含 0、2、12、44、75、81 (查看 columnA 中的 33 个不同的数值。如果 columnA 包含定义的 33 个值中的 1 个,则我在尝试修改值时遇到问题,我需要然后更改同一行的 colulmnB 为“已批准”。
我试过这个:df[(df.columnA == '0|2|12|44|75|81')][df.columnB] = 'approved'
我收到一个错误,即列中没有索引,但是我知道查看我的 csv 文件数据是不正确的。我一定是搜索错误或使用了错误的语法。
解决方案
正如其他人所说,如果您需要 A 列中的值与列表中的值完全匹配,那么您可以使用 .isin。如果您需要部分匹配,则可以转换为字符串 dtypes 并使用 .contains。
设置:
nums_to_match = [0,2,9]
df
A B
0 6 e
1 1 f
2 3 b
3 6 g
4 6 i
5 0 f
6 9 a
7 6 i
8 6 a
9 2 h
完全符合:
df.loc[df.A.isin(nums_to_match),'B']='approved'
df:
A B
0 6 e
1 1 f
2 3 b
3 6 g
4 6 i
5 0 approved
6 9 approved
7 6 i
8 6 a
9 2 approved
部分匹配:
nums_to_match_str = list(map(str,nums_to_match))
df['A']=df['A'].astype(str)
df.loc[df.A.str.contains('|'.join(nums_to_match_str),case=False,na=False),'B']='approved'
df
A B
0 1 h
1 4 c
2 6 i
3 7 d
4 3 d
5 9 approved
6 5 i
7 1 c
8 0 approved
9 5 d
推荐阅读
- swift - Firestore中的“DatabaseHandle”等价物是什么?
- excel - 重新标记图表系列集合
- ruby - 在 Sketchup 中使用 Ruby 复制浮点数
- javascript - React Native 和 Apollo:找不到变量:文档
- java - GridPane 元素最初超出边界,仅在调整窗口大小后才卡入到位
- flutter - 有没有办法在颤动中自动单击按钮?
- python - 如何在 PyCharm 远程 SSH 解释器 (SFTP) 中使用 opencv 使用网络摄像头 - Python
- bots - 是否可以创建一个松弛的日期时间选择器元素?
- android - ionic cordova android build error(cordova.cmd build android exited with exit code 1)
- arrays - 如何在 Python 中打印这个二维数组