本文介绍了如何处理“被零除"?处理列时使用pandas dataframes?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working with hundreds of pandas dataframes. A typical dataframe is as follows:

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
....

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

There are certain operations whereby I'm dividing between columns values, e.g.

df['one']/df['two'] 

但是,有时我会被零除,或者可能两者都被除

However, there are times where I am dividing by zero, or perhaps both

df['one'] = 0
df['two'] = 0

自然,这将输出错误:

ZeroDivisionError: division by zero

我希望0/0实际表示这里什么也没有",因为在数据帧中通常这样的零表示.

I would prefer for 0/0 to actually mean "there's nothing here", as this is often what such a zero means in a dataframe.

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

(a) How would I code this to mean "divide by zero" is 0 ?

(b)如果遇到被零除的情况,我该如何编码为通过"?

(b) How would I code this to "pass" if divide by zero is encountered?

推荐答案

要考虑的两种方法:

通过显式编码无数据"值并对其进行测试,以使数据永远不会被零除.

Prepare your data so that never has a divide by zero situation, by explicitly coding a "no data" value and testing for that.

try/except对包装可能导致错误的每个除法. > https://wiki.python.org/moin/HandlingExceptions (使用除以零的示例)

Wrap each division that might result in an error with a try/except pair, as described at https://wiki.python.org/moin/HandlingExceptions (which has a divide by zero example to use)

(x,y) = (5,0)
try:
  z = x/y
except ZeroDivisionError:
  print "divide by zero"

我担心您的数据中包含的零实际上是零(而不是缺失值).

I worry about the situation where your data includes a zero that's really a zero (and not a missing value).

这篇关于如何处理“被零除"?处理列时使用pandas dataframes?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 22:16