我有一个与此类似的数据集:
d = {
'col1': [1,2,3,4,2,4,1,3,5,3,2,2,1,5],
'col2': [2,1,5,2,4,1,3,3,3,2,2,4,2,1]
}
df = pd.DataFrame(data=d)
它是:
col1 col2
0 1 2
1 2 1
2 3 5
3 4 2
4 2 4
5 4 1
6 1 3
7 3 3
8 5 3
9 3 2
10 2 2
11 2 4
12 1 2
13 5 1
我想对只有一列的单元格内容进行“分类”,假设是 col2。例如,如果单元格的值为 2、3 或 4,我想将其替换为值 7。我已尝试以下操作:
for row in df.itertuples():
if row.col2==2 or row.P28==3 or row.P28==4:
df1.set_value(row, 'P28', 7)
但是错误
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
被返回。我不确定为什么会收到此错误以及应该如何使用建议的功能。
最佳答案
幸运的是,您不需要循环:
mask = df['col2'].isin([2,3,4]) # Create a boolean mask of the condition
df.loc[mask, 'col2'] = 7 # Replace values based on boolean mask
df
# col1 col2
# 0 1 7
# 1 2 1
# 2 3 5
# 3 4 7
# 4 2 7
# 5 4 1
# 6 1 7
# 7 3 7
# 8 5 7
# 9 3 7
# 10 2 7
# 11 2 7
# 12 1 7
# 13 5 1
关于python - 使用 pandas 根据条件替换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48175334/