我有这个数据框
import pandas as pd
x = pd.DataFrame.from_dict({'A':[1,2,0,4,0,6], 'B':[0, 0, 0, 44, 48, 81], 'C':[1,0,1,0,1,0]})
我尝试像这样更改它,但不起作用
x[x['A']>3]['A'] = 33 # has no effect
我也尝试过
x.loc(x['A']>3)['A'] = 33 # getting an error
那么正确的方法是什么?
答案 0 :(得分:0)
您应该使用.loc
x.loc[x['A']>3,'A'] = 33
x
Out[480]:
A B C
0 1 0 1
1 2 0 0
2 0 0 1
3 33 44 0
4 0 48 1
5 33 81 0
或mask
x.A=x.mask(x.A>3,33)
x
Out[483]:
A B C
0 1 0 1
1 2 0 0
2 0 0 1
3 33 44 0
4 0 48 1
5 33 81 0