【发布时间】:2017-10-04 16:25:07
【问题描述】:
我的数据框如下所示:
>>>df1
ARP CDP
DATE
2017-09-15 03:49:00 -1.81 -1.81
2017-09-15 11:30:00 -2.70 -2.70
2017-09-15 13:15:00 -2.70 -2.70
2017-09-15 16:03:00 -2.70 -2.70
>>>df1.dtypes
ARP float64
CDP float64
dtype: object
我有以下function:
def lookup(value1, value2):
print type(value1)
value1 = round(value1, 5)
value2 = round(value2, 5)
if value1 == value2:
return 0.0
else:
diff = abs(value1 - value2)
if diff == inf:
return 100.0
elif math.isnan(diff):
return 100.0
else:
return diff
现在当我运行以下命令时:
df1['DIFF'] = df1.apply(lambda x: lookup(x[df1.columns[0]], x[df1.columns[1]]), axis=1)
我收到以下错误:
<class 'pandas.core.series.Series'>
Traceback (most recent call last):
df1['DIFF'] = df1.apply(lambda x: lookup(x[df1.columns[0]],
x[df1.columns[1]]), axis=1)
File blah, line 3718, in apply
return self._apply_standard(f, axis, reduce=reduce)
File "/pandas/core/frame.py", line 3808, in _apply_standard
results[i] = func(v)
File "<ipython-input-688-449dea597035>", line 29, in <lambda>
df1['DIFF'] = df1.apply(lambda x: lookup(x[df1.columns[0]],
x[df1.columns[1]]), axis=1)
File "<ipython-input-669-c78026996809>", line 5, in lookup
if value1 == value2:
File "/pandas/core/generic.py", line 714, in __nonzero__
.format(self.__class__.__name__))
ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', u'occurred at index 1993-06-04 15:25:00')
不知道为什么!!理想情况下,我只想创建另一个名为 DIFF 的列,它要么返回 0,要么返回其他两列的差异。
谢谢
【问题讨论】:
-
更糟糕的是...我没有收到此错误。使用 python 3.6 和 pandas 0.20.3 为我工作。当然,我删除了打印语句。
标签: python pandas dataframe lambda apply