存储为Pandas DataFrame
print(df)
col1 | col2
A | 1
B | 3
C | 3
D | 7
E | 4
C | 3
我想创建一个新列,如果col1是A,C或E,则向col2加1。
col1 | col2 | col2_corrected
A | 1 | 2
B | 3 | 3
C | 3 | 4
D | 7 | 7
E | 4 | 5
C | 3 | 4
add_one_to_me = ['A','C','E']
if df.col1.isin(add_one_to_me):
df.col2_corrected = df.col2 + 1
else: df.col2_corrected = df.col2
由于正在评估整个系列的真实性,因此引发了关于歧义性真实性的错误。
如何将其应用于DataFrame的每一行?我是Python和编程的新手,所以这是一个非常基本的问题。
提前致谢!
# Copy the existing column over
df['col2_corrected'] = df.col2
# Increment the values of only those items where col1 is A C or E
df.loc[df.col1.isin(['A', 'C', 'E']), 'col2_corrected'] += 1
df
Out[]:
col1 col2 col2_corrected
0 A 1 2
1 B 3 3
2 C 3 4
3 D 7 7
4 E 4 5
5 C 3 4
您收到该错误的原因是因为 if df.col1.isin(add_one_to_me):
如果我们看一下: df.col1.isin(add_one_to_me)
Out[]:
0 True
1 False
2 True
3 False
4 True
5 True
这并不意味着该if
声明。您可以做的是迭代检查每个项目col1
,然后递增col2_corrected
一个。这可以通过使用df.apply(...)
或来完成for index, row in df.iterrows():
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句