如何在Python DataFrame中为按行过滤的单元格设置值?

Pal*_*ule 4 python python-3.x pandas

import pandas as pd

df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9],[10,11,12]],columns=['A','B','C'])
df[df['B']%2 ==0]['C'] = 5
Run Code Online (Sandbox Code Playgroud)

我期望这段代码将 C 列的值更改为 5,只要 B 为偶数。但它不起作用。

它返回的表如下

    A   B   C
0   1   2   3
1   4   5   6
2   7   8   9
3   10  11  12
Run Code Online (Sandbox Code Playgroud)

我期待它回来

    A   B   C
0   1   2   5
1   4   5   6
2   7   8   5
3   10  11  12
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 5

如果需要更改列的值,则DataFrame需要DataFrame.loc使用条件和列名称:

df.loc[df['B']%2 ==0, 'C'] = 5
print (df)
    A   B   C
0   1   2   5
1   4   5   6
2   7   8   5
3  10  11  12
Run Code Online (Sandbox Code Playgroud)

您的解决方案是链式索引的一个很好的例子 -文档