gpt4 book ai didi

python - Pandas 变量移位错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:44 24 4
gpt4 key购买 nike

在下面的示例中,第一个应用有效。第二个抛出“TypeError: ("Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe'", u'occurred at index 0')"

df = pd.DataFrame({'lag':[ 3, 5, 3, 4, 2, 3, 2, 3, 4, 3, 2, 2, 2, 3],
'A':[10,20,30,40,20,30,40,10,20,30,15,60,20,15],
'B':[11,21,31,41,21,31,41,11,21,31,15,61,21,25]})
df['C'] = df.apply(lambda x: df['A'].shift(x['lag'])[x.name], axis=1)
print df
df['D'] = df.apply(lambda x: df['B'].shift(x['lag'])[x.name], axis=1)
print df

请告诉我为什么会发生这种情况以及如何解决它。谢谢,

(注意:我没有足够的“积分”在 Variable shift in Pandas 发表评论)

最佳答案

这实际上是一件棘手的事情。我会尽量简洁。

当您将 applyaxis=1 一起使用时,您将逐行迭代。对于每一行,pandas 将其作为 pd.Series 进行处理。初始赋值后,将 NaN 值放入 df 访问该行时,整行将被解释为 float


解决 #1
确保滞后值为 int

df['D'] = df.apply(lambda x: df['B'].shift(int(x['lag']))[x.name], axis=1)

解决 #2
同时做作业

df = df.assign(
C=df.apply(lambda x: df['A'].shift(x['lag'])[x.name], axis=1),
D=df.apply(lambda x: df['B'].shift(int(x['lag']))[x.name], axis=1)
)

更好的解决方案
但是,我会使用 numpy 来帮助解决这个问题

那些滞后只是当前位置值减去滞后值

l = (np.arange(len(df)) - df.lag.values)

然后

df['C'] = np.where(l >= 0, df.A.values[l], np.nan)
df['D'] = np.where(l >= 0, df.B.values[l], np.nan)

关于python - Pandas 变量移位错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42773199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com