我有以下数据框:
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
我想做的是将所有小于 1 的值替换为 0。 产量:
0 1
qux 0 4.10
foo 0 0
bar 1.0 0
我怎样才能做到这一点?
最佳答案
使用 bool 索引并传递条件:
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
将返回一个 bool 索引:
In [156]:
df < 1
Out[156]:
0 1
bar False True
foo True True
qux True False
然后我们将其传递给 df
作为掩码,然后可以将新值分配为 df[df<1]
查看docs更多例子
关于python - 如何用条件替换 Pandas 数据框中所有列中的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27857475/