I've created a pandas DataFrame
df = DataFrame(np.arange(15).reshape(3,5), columns=['a','b','c', 'd', 'e'])
df a b c d e
0 0 1 2 3 4
1 5 6 7 8 9
2 10 11 12 13 14
And I want to set values for particular cells:
flag = df['b'] > 3
df[flag]['b']=10
But it doesn't work.
df a b c d e
0 0 1 2 3 4
1 5 6 7 8 9
2 10 11 12 13 14
I use the following codes. It works, but i don't know why?
df['b'][flag] = 10
df a b c d e
0 0 1 2 3 4
1 5 10 7 8 9
2 10 10 12 13 14
Do not use chained indexing for assigning values.
Instead, use pd.DataFrame.loc
to specify rows and columns:
df.loc[df['b'] > 3, 'b'] = 10
The .loc
indexer accepts lists, scalars, or Boolean arrays.
The pandas
docs explain in detail why chained indexing should be avoided.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.