使用数据框df:
ID | Category | Price
23 A 101
34 B 50
24 A 55
我想为所有A类和价格小于等级100添加一个标志。
这是我的代码:
df['Flag'][(df['Price'] <=100)&(df['Category']=='A')] = 'X'
我收到此错误:
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
当我尝试过滤标志时,我收到此错误:
df.loc[df['Flag'] == 'X']
TypeError: invalid type comparison
预期产出:
ID | Category | Price Flag
23 A 101
34 B 50
24 A 55 X
答案 0 :(得分:1)
使用loc
df.loc[(df['Price'] <=100)&(df['Category']=='A'), "Flag"] = 'X'
答案 1 :(得分:1)
您可以使用map()
:
>>> df['flag'] = ((df['Category'] == 'A') & (df['Price'] <= 100)).map({True: 'X', False: ''})
>>> df
ID Category Price flag
0 23 A 101
1 34 B 50
2 24 A 55 X