且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何用条件替换Pandas数据框中所有列中的所有值

更新时间:2023-01-20 11:16:54

使用布尔索引并传递条件:

Use boolean indexing and pass the condition:

In [155]:
df[df<1] = 0
df
Out[155]:
     0    1
bar  1  0.0
foo  0  0.0
qux  0  4.1

仅显示在这里执行df < 1会发生什么,将返回一个布尔索引:

Just to show what is happening here performing df < 1 will return a boolean index:

In [156]:
df < 1
Out[156]:
         0      1
bar  False   True
foo   True   True
qux   True  False

然后我们将其作为掩码传递给df,然后可以将新值指定为df[df<1],请参见

This we then pass to df as a mask and can then assign the new values as df[df<1] see the docs for further examples