使用pandas替换基于条件的值

时间:2018-01-09 19:26:00

标签: python python-2.7 pandas

我有一个与此类似的数据集:

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

我想'分类'ONLY ONE列的单元格的内容,让我们说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().

返回。我不知道为什么我会收到此错误,我应该如何使用任何建议的功能。

2 个答案:

答案 0 :(得分:2)

幸运的是,你不需要循环:

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

答案 1 :(得分:1)

您可以使用字典替换

d = dict.fromkeys([2,3,4], 7)
df['col2'] = df.col2.replace(d)

    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