如何使用条件替换 Pandas 数据框中所有列中的所有值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27857475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to replace all value in all columns in a Pandas dataframe with condition
提问by pdubois
I have the following data frame:
我有以下数据框:
In [11]: import pandas as pd
In [12]: mydict = {'foo':[0, 0.3], 'bar':[1,0.55], 'qux': [0.3,4.1]}
In [13]: df = pd.DataFrame.from_dict(mydict, orient='index')
In [14]: df
Out[14]:
0 1
qux 0.3 4.10
foo 0.0 0.30
bar 1.0 0.55
What I want to do is to replace all values that is less than 1 with 0. Yielding:
我想要做的是用 0 替换所有小于 1 的值。产量:
0 1
qux 0 4.10
foo 0 0
bar 1.0 0
How can I achieve that?
我怎样才能做到这一点?
采纳答案by EdChum
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
Just to show what is happening here performing df < 1will return a boolean index:
只是为了展示这里发生的事情,表演df < 1将返回一个布尔索引:
In [156]:
df < 1
Out[156]:
0 1
bar False True
foo True True
qux True False
This we then pass to dfas a mask and can then assign the new values as df[df<1]see the docsfor further examples
然后我们将其df作为掩码传递给,然后可以分配新值,如有关更多示例df[df<1]的文档

