python-如何用z替换熊猫数据框中的负数

我想知道是否有某种方式将所有DataFrame负数替换为零?

Hangon asked 2020-07-31T02:23:50Z
5个解决方案
69 votes

如果所有列都是数字列,则可以使用布尔索引:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1]})

In [3]: df
Out[3]: 
   a  b
0  0 -3
1 -1  2
2  2  1

In [4]: df[df < 0] = 0

In [5]: df
Out[5]: 
   a  b
0  0  0
1  0  2
2  2  1

对于更一般的情况,此答案显示了私有方法timedelta

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1],
                           'c': ['foo', 'goo', 'bar']})

In [3]: df
Out[3]: 
   a  b    c
0  0 -3  foo
1 -1  2  goo
2  2  1  bar

In [4]: num = df._get_numeric_data()

In [5]: num[num < 0] = 0

In [6]: df
Out[6]: 
   a  b    c
0  0  0  foo
1  0  2  goo
2  2  1  bar

对于timedelta类型,布尔索引似乎适用于单独的列,但不适用于整个数据框。 因此,您可以执行以下操作:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'a': pd.to_timedelta([0, -1, 2], 'd'),
   ...:                    'b': pd.to_timedelta([-3, 2, 1], 'd')})

In [3]: df
Out[3]: 
        a       b
0  0 days -3 days
1 -1 days  2 days
2  2 days  1 days

In [4]: for k, v in df.iteritems():
   ...:     v[v < 0] = 0
   ...:     

In [5]: df
Out[5]: 
       a      b
0 0 days 0 days
1 0 days 2 days
2 2 days 1 days

更新:与pd.Timedelta的比较适用于整个DataFrame:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'a': pd.to_timedelta([0, -1, 2], 'd'),
   ...:                    'b': pd.to_timedelta([-3, 2, 1], 'd')})

In [3]: df[df < pd.Timedelta(0)] = 0

In [4]: df
Out[4]: 
       a      b
0 0 days 0 days
1 0 days 2 days
2 2 days 1 days
Lev Levitsky answered 2020-07-31T02:24:19Z
39 votes

另一个简洁的方法是pandas.DataFrame.clip。

例如:

import pandas as pd

In [20]: df = pd.DataFrame({'a': [-1, 100, -2]})

In [21]: df
Out[21]: 
     a
0   -1
1  100
2   -2

In [22]: df.clip(lower=0)
Out[22]: 
     a
0    0
1  100
2    0

还有df.clip_lower(0)

follyroof answered 2020-07-31T02:24:47Z
8 votes

也许您可以像这样使用pandas.where(args)

data_frame = data_frame.where(data_frame < 0, 0)
aus_lacy answered 2020-07-31T02:25:07Z
2 votes

如果您要处理大型df(在我的情况下为40m x 700),则它的工作速度会更快,并且通过类似这样的列迭代可以节省内存。

for col in df.columns:
    df[col][df[col] < 0] = 0
MarKo9 answered 2020-07-31T02:25:27Z
0 votes

我发现另一个有用的干净选项是pandas.DataFrame.mask,它将“替换条件为真的值”。

创建数据框:

In [2]: import pandas as pd

In [3]: df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1]})

In [4]: df
Out[4]: 
   a  b
0  0 -3
1 -1  2
2  2  1

将负数替换为0:

In [5]: df.mask(df < 0, 0)
Out[5]: 
   a  b
0  0  0
1  0  2
2  2  1

或者,将NaN替换为负数,这是我经常需要的:

In [7]: df.mask(df < 0)
Out[7]: 
     a    b
0  0.0  NaN
1  NaN  2.0
2  2.0  1.0
Michael Conlin answered 2020-07-31T02:26:00Z
translate from https://stackoverflow.com:/questions/27759084/how-to-replace-negative-numbers-in-pandas-data-frame-by-zero