在操作列时如何使用pandas数据帧处理"除以零"?

Sha*_*ang 6 python dataframe python-3.x pandas

我正在处理数百个熊猫数据帧.典型的数据框如下:

import pandas as pd
import numpy as np
data = 'filename.csv'
df = pd.DataFrame(data)
df 

        one       two     three  four   five
a  0.469112 -0.282863 -1.509059  bar   True
b  0.932424  1.224234  7.823421  bar  False
c -1.135632  1.212112 -0.173215  bar  False
d  0.232424  2.342112  0.982342  unbar True
e  0.119209 -1.044236 -0.861849  bar   True
f -2.104569 -0.494929  1.071804  bar  False
....
Run Code Online (Sandbox Code Playgroud)

有些操作我在列值之间进行划分,例如

df['one']/df['two'] 
Run Code Online (Sandbox Code Playgroud)

但是,有时我会将其除以零,或者两者兼而有之

df['one'] = 0
df['two'] = 0
Run Code Online (Sandbox Code Playgroud)

当然,这会输出错误:

ZeroDivisionError: division by zero
Run Code Online (Sandbox Code Playgroud)

我宁愿0/0实际上意味着"这里没有任何东西",因为这通常是数据帧中的零意味着什么.

(a)我如何将其编码为"除以零"为0?

(b)如果遇到零除,我如何将其编码为"通过"?

Ale*_*der 18

使用分母中实际为零的数据帧可能更有用(请参阅列的最后一行two).

        one       two     three   four   five
a  0.469112 -0.282863 -1.509059    bar   True
b  0.932424  1.224234  7.823421    bar  False
c -1.135632  1.212112 -0.173215    bar  False
d  0.232424  2.342112  0.982342  unbar   True
e  0.119209 -1.044236 -0.861849    bar   True
f -2.104569  0.000000  1.071804    bar  False

>>> df.one / df.two
a   -1.658442
b    0.761639
c   -0.936904
d    0.099237
e   -0.114159
f        -inf  # <<< Note division by zero
dtype: float64
Run Code Online (Sandbox Code Playgroud)

当其中一个值为零时,您应该得到inf或者-inf在结果中.转换这些值的一种方法如下:

df['result'] = df.one.div(df.two)

df.loc[~np.isfinite(df['result']), 'result'] = np.nan  # Or = 0 per part a) of question.
# or df.loc[np.isinf(df['result']), ...

>>> df
        one       two     three   four   five    result
a  0.469112 -0.282863 -1.509059    bar   True -1.658442
b  0.932424  1.224234  7.823421    bar  False  0.761639
c -1.135632  1.212112 -0.173215    bar  False -0.936904
d  0.232424  2.342112  0.982342  unbar   True  0.099237
e  0.119209 -1.044236 -0.861849    bar   True -0.114159
f -2.104569  0.000000  1.071804    bar  False       NaN
Run Code Online (Sandbox Code Playgroud)

  • 我认为这没有解决有关 ZeroDivisionError 的问题。当我除以零时,我不会得到“inf”。我收到 ZeroDivisionError。 (3认同)
  • 小澄清:只要两列的数据类型是“float”,这就可以工作。对于 int 则不会。因此,如果您遇到德鲁提到的问题,只需将您的列转换为在除法之前浮动即可。 (2认同)

Kar*_*tik 10

df['one'].divide(df['two'])
Run Code Online (Sandbox Code Playgroud)

代码:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.rand(5,2), columns=list('ab'))
df.loc[[1,3], 'b'] = 0
print(df)

print(df['a'].divide(df['b']))
Run Code Online (Sandbox Code Playgroud)

结果:

    a           b
0   0.517925    0.305973
1   0.900899    0.000000
2   0.414219    0.781512
3   0.516072    0.000000
4   0.841636    0.166157

0    1.692717
1         inf
2    0.530023
3         inf
4    5.065297
dtype: float64
Run Code Online (Sandbox Code Playgroud)

  • 这个答案似乎没有回答问题。解决方案是使用:`df['one'].div(df['two']).replace(np.inf, 0)`。 (8认同)

vie*_*tti -4

需要考虑的两种方法:

通过显式编码“无数据”值并对其进行测试,准备数据,以便永远不会出现被零除的情况。

将可能导致错误的每个除法用try/对括起来,如https://wiki.python.org/moin/HandlingExceptionsexcept中所述(其中有一个除以零的示例可供使用)

(x,y) = (5,0)
try:
  z = x/y
except ZeroDivisionError:
  print "divide by zero"
Run Code Online (Sandbox Code Playgroud)

我担心您的数据包含一个真正的零(而不是缺失值)的零。

  • Pandas(或 NumPy)不会引发 ZeroDivisionError。 (20认同)
  • @ayhan 我从使用 pandas `div` 函数时收到 ZeroDivisionError 。文件“processing.py”,第 50 行,有趣 || df['pct'] = df['diffs', '2019-11-13'].divide(df['shares_latest']) || 文件“pandas/core/ops/__init__.py”,第 570 行,在 flex_wrapper || 中 返回 self._binop(其他, op, level=level, fill_value=fill_value) || 文件“pandas/core/series.py”,第 2618 行,在 _binop || 中 结果 = func(this_vals, other_vals) || ZeroDivisionError:浮点数除以零 (6认同)