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

时间:2018-06-01 09:31:55

标签: python 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

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

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

1 个答案:

答案 0 :(得分:3)

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

而是使用pd.DataFrame.loc指定行和列:

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

.loc索引器接受列表,标量或布尔数组。

pandas docs explain in detail为什么应该避免使用链式索引。

相关问题