python - 如何计算相对值再平衡的if语句/错误: "The truth value of a Series is ambiguous"

标签 python pandas

下面是我编写的代码,用于计算 df.a 和 df.b 值的相对变化,而 df 是数据帧。需要计算的基本上是df["c"] = df.a/df.a.iloc[df.d].values .如果 df.a/df.a.iloc[df.d].values,df.d 设置为等于 df.t大于或小于 df.b/df.b.iloc[df.d].values * (1+ tolerance)

问题是代码当前带来以下错误代码: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 2011-01-01 00:00:00')我完全不知道为什么...

import pandas as pd
import numpy as np
import datetime

randn = np.random.randn
rng = pd.date_range('1/1/2011', periods=10, freq='D')

df = pd.DataFrame({'a': [1.1, 1.2, 2.3, 1.4, 1.5, 1.8, 0.7, 1.8, 1.9, 2.0], 'b': [1.1, 1.5, 1.3, 1.6, 1.5, 1.1, 1.5, 1.7, 2.1, 2.1],'c':[None] * 10},index=rng)

df["d"]= [0,0,0,0,0,0,0,0,0,0]
df["t"]= np.arange(len(df))
tolerance = 0.3

def set_t(x):
    if df.a/df.a.iloc[df.d].values < df.b/df.b.iloc[df.d].values * (1+tolerance):
        return  df.iloc[df.index.get_loc(x.name) - 1]['d'] == df.t
    elif df.a/df.a.iloc[df.d].values > df.b/df.b.iloc[df.d].values * (1+tolerance):
        return df.iloc[df.index.get_loc(x.name) - 1]['d'] == df.t

#The conditions in part one are exactly the same as in part 2, only first it says smaller than, and in the second part is bigger than df.b/df.b.iloc[df.d].values * (1+tolerance)


df['d'] = df.apply(set_t, axis =1)

#df["d"]= [0,0,0,3,3,3,6,7,7,7] this should be the coutcome for d

df["c"] = df.a/df.a.iloc[df.d].values 

申请(df.a/df.a.iloc[df.d].values).all() < (df.b/df.b.iloc[df.d].values).all().any()不会导致预期的结果,因为它仅检查当前设置的数据何时为 TRUE 或 FALSE,但不会设置新值。

期望的结果如下所示:

              a    b         c  d  t
2011-01-01  1.1  1.1  1.000000  0  0
2011-01-02  1.2  1.5  1.090909  0  1
2011-01-03  2.3  1.3  2.090909  0  2
2011-01-04  1.4  1.6  1.000000  3  3
2011-01-05  1.5  1.5  1.071429  3  4
2011-01-06  1.8  1.1  1.285714  3  5
2011-01-07  0.7  1.5  1.000000  6  6
2011-01-08  1.8  1.7  1.000000  7  7
2011-01-09  1.9  2.1  1.055556  7  8
2011-01-10  2.0  2.1  1.111111  7  9

有什么解决办法吗?

最佳答案

这不是 100% 的解决方案,但至少应该让您走上更好的道路并解决主要问题。我在这里从语法方面看到的核心问题是您试图混合矢量化和非矢量化代码。你可以改为做更像这样的事情:

>>> df['d1'] = df.a/df.a.iloc[df.d].values > df.b/df.b.iloc[df.d].values * (1+tolerance)

>>> df['d2'] = df.a/df.a.iloc[df.d].values * (1+tolerance) < df.b/df.b.iloc[df.d].values

>>> df['d'] = df['d1'] | df['d2']

>>> df

              a    b     c      d  t     d1     d2
2011-01-01  1.1  1.1  None  False  0  False  False
2011-01-02  1.2  1.5  None  False  1  False  False
2011-01-03  2.3  1.3  None   True  2   True  False
2011-01-04  1.4  1.6  None  False  3  False  False
2011-01-05  1.5  1.5  None  False  4  False  False
2011-01-06  1.8  1.1  None   True  5   True  False
2011-01-07  0.7  1.5  None   True  6  False   True
2011-01-08  1.8  1.7  None  False  7  False  False
2011-01-09  1.9  2.1  None  False  8  False  False
2011-01-10  2.0  2.1  None  False  9  False  False

这不是您想要的答案,但希望向您展示代码中发生了什么,以及如何修复它以获得您想要的结果(即您不需要或不想使用一个函数并应用它在这里,只需使用标准的 pandas 矢量化代码即可)。

如果你能让它工作,更简洁的方法是使用 np.where(其中两个顺序或嵌套)。

关于python - 如何计算相对值再平衡的if语句/错误: "The truth value of a Series is ambiguous",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30682918/

相关文章:

python - 如何根据多个条件将值插入数据框?逻辑问题

python - "ValueError: Length of values does not match length of index"尝试修改 pandas groupby 的列值时

python - python 上的 LMFIT 置信区间不确定性估计误差

python - 如何获取 ImageDataGenerator.flow_from_directory Keras 中的值列表?

python - 使用相似矩阵的 sklearn 层次凝聚聚类

python - Pandas:read.csv() - 只读具有特定列长度的行

python - 来自 pymongo 的游标列表理解

python - django - 基本模板中的静态文件

Python:迭代字典时出现问题

python - 不支持 Pandas 逻辑回归混合类型?