[英]How to set values for particular cells in pandas.Dataframe correctly?
I've created a pandas DataFrame 我已经创建了一个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: 而是使用pd.DataFrame.loc
指定行和列:
df.loc[df['b'] > 3, 'b'] = 10
The .loc
indexer accepts lists, scalars, or Boolean arrays. .loc
索引器接受列表,标量或布尔数组。
The pandas
docs explain in detail why chained indexing should be avoided. pandas
文档详细解释了为什么应该避免链式索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.