gpt4 book ai didi

python - 如何使用基于Python中列中先前值的函数创建列

转载 作者:行者123 更新时间:2023-12-01 07:17:38 24 4
gpt4 key购买 nike

我的问题

我有一个循环,它根据时间段 t-1 中的 x 创建时间段 t 中 x 的值。循环真的很慢,所以我想尝试将其变成一个函数。我尝试将 np.where 与 shift() 一起使用,但我没有任何乐趣。知道我如何解决这个问题吗?

谢谢!

我的代码

import numpy as np
import pandas as pd

csv1 = pd.read_csv('y_list.csv', delimiter = ',')
df = pd.DataFrame(csv1)

df.loc[df.index[0], 'var'] = 0

for x in range(1,len(df.index)):
if df["LAST"].iloc[x] > 0:
df["var"].iloc[x] = ((df["var"].iloc[x - 1] * 2) + df["LAST"].iloc[x]) / 3
else:
df["var"].iloc[x] = (df["var"].iloc[x - 1] * 2) / 3

df

输入数据

Dates,LAST
03/09/2018,-7
04/09/2018,5
05/09/2018,-4
06/09/2018,5
07/09/2018,-6
10/09/2018,6
11/09/2018,-7
12/09/2018,7
13/09/2018,-9

输出

Dates,LAST,var
03/09/2018,-7,0.000000
04/09/2018,5,1.666667
05/09/2018,-4,1.111111
06/09/2018,5,2.407407
07/09/2018,-6,1.604938
10/09/2018,6,3.069959
11/09/2018,-7,2.046639
12/09/2018,7,3.697759
13/09/2018,-9,2.465173

最佳答案

您正在查看ewm :

arg = df.LAST.clip(lower=0)
arg.iloc[0] = 0
arg.ewm(alpha=1/3, adjust=False).mean()

输出:

0    0.000000
1 1.666667
2 1.111111
3 2.407407
4 1.604938
5 3.069959
6 2.046639
7 3.697759
8 2.465173
Name: LAST, dtype: float64

关于python - 如何使用基于Python中列中先前值的函数创建列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57870648/

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