首页 > 解决方案 > 麻烦根据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 文件数据是不正确的。我一定是搜索错误或使用了错误的语法。

标签: python-3.xpandasdataframe

解决方案


正如其他人所说,如果您需要 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

推荐阅读