如何用条件替换熊猫数据存储器中所有列中的所有值

时间:2022-03-13 22:57:59

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?

我怎么能做到呢?

1 个解决方案

#1


9  

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 < 1 will 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 df as a mask and can then assign the new values as df[df<1] see the docs for further examples

然后我们将其作为掩码传递给df,然后可以将新的值赋值为df[df<1],请参阅文档以获得更多的示例

#1


9  

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 < 1 will 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 df as a mask and can then assign the new values as df[df<1] see the docs for further examples

然后我们将其作为掩码传递给df,然后可以将新的值赋值为df[df<1],请参阅文档以获得更多的示例