当前数据:
存储为 Pandas DataFrame
print(df)
col1 | col2
A | 1
B | 3
C | 3
D | 7
E | 4
C | 3
目标:
我想创建一个新列,如果 col1 是 A、C 或 E,则将 1 添加到 col2。
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 递增1。这可以通过使用 df.apply(...) 或 for index, row in df.iterrows():
