gpt4 book ai didi

python - 如何正确设置 pandas.Dataframe 中特定单元格的值?

转载 作者:行者123 更新时间:2023-11-30 22:13:56 28 4
gpt4 key购买 nike

我创建了一个 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

我想为特定单元格设置值:

flag = df['b'] > 3 

df[flag]['b']=10

但是它不起作用

df  a   b   c   d   e
0 0 1 2 3 4
1 5 6 7 8 9
2 10 11 12 13 14

我使用以下代码。 它有效,但我不知道为什么?

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

最佳答案

不要使用链式索引来分配值。

相反,请使用 pd.DataFrame.loc指定行和列:

df.loc[df['b'] > 3, 'b'] = 10

.loc 索引器接受列表、标量或 bool 数组。

pandas 文档 explain in detail为什么应避免链式索引。

关于python - 如何正确设置 pandas.Dataframe 中特定单元格的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50640334/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com