熊猫 df 列中的布尔函数 - 面向对象 - 序列的模糊真值



我需要一些帮助来创建包含布尔函数的数据帧列。 我想根据有关其他 df 列数据的条件接收 True 或 False 的值。

数据帧:

date    C   A
0   2020-02-04  3284.75 3284.75
1   2020-02-05  3322.25 3303.50
2   2020-02-06  3333.25 3327.75
3   2020-02-07  3315.50 3324.38
4   2020-02-10  3340.25 3327.88
5   2020-02-11  3345.50 3342.88
6   2020-02-12  3367.00 3356.25
7   2020-02-13  3363.50 3365.25
8   2020-02-14  3368.25 3365.88

这是函数:

def func(C, A):
for i in range(3):
if C.shift(i) >= A.shift(i):
j + 1
if j == 3:
val = True
else:
val = False
return val

在这里,我调用该函数:

data['Func'] = data.apply(func(data['C'], data['A']), axis=1)

我在此示例中遇到的错误是

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

我试图让它工作时收到的最常见的错误是

TypeError: 'DatetimeIndex' object is not callable

AttributeError: ("'numpy.float64' object has no attribute 'shift'",

在这一点上,我不确定哪些元素有效或不起作用。 任何帮助将不胜感激。 提前谢谢。

  • .apply就像一个美化的for-loop,这意味着函数中的CA分别等于一个值,而不是一个系列。因此shift不起作用。
  • 你可以试试np.where
  • 预期的输出并不完全清楚,所以希望这会让你走上正确的轨道。
import numpy as np
df['Func'] = np.where((df.C.shift(0) >= df.A.shift(0)) & (df.C.shift(1) >= df.A.shift(1)) & (df.C.shift(2) >= df.A.shift(2)), True, False)
display(df)
C        A   Func
3284.75  3284.75  False
3322.25  3303.50  False
3333.25  3327.75   True
3315.50  3324.38  False
3340.25  3327.88  False
3345.50  3342.88  False
3367.00  3356.25   True
3363.50  3365.25  False
3368.25  3365.88  False

解释

  • 对于每一行,必须True每个条件才能FuncTrue

shift(0)

df.C.shift(0) >= df.A.shift(0)
date
2020-02-04     True
2020-02-05     True
2020-02-06     True
2020-02-07    False
2020-02-10     True
2020-02-11     True
2020-02-12     True
2020-02-13    False
2020-02-14     True

shift(1)

df.C.shift(1) >= df.A.shift(1)
date
2020-02-04    False
2020-02-05     True
2020-02-06     True
2020-02-07     True
2020-02-10    False
2020-02-11     True
2020-02-12     True
2020-02-13     True
2020-02-14    False

shift(2)

df.C.shift(2) >= df.A.shift(2)
date
2020-02-04    False
2020-02-05    False
2020-02-06     True
2020-02-07     True
2020-02-10     True
2020-02-11    False
2020-02-12     True
2020-02-13     True
2020-02-14     True

最新更新