gpt4 book ai didi

pandas - "Indexing"到起始时间点(指数水平 = 100)的价格序列,带有 pandas 数据框 : P(i, t)/P(i)

转载 作者:行者123 更新时间:2023-12-04 16:45:52 25 4
gpt4 key购买 nike

我有一个 pandas 数据框,其中 datetime 是数据框的索引(我使用 t=0 来简化,实际上有类似 20170101 09:30:00 的东西)

datetime    Stock A    Stock B
t=0 5 20
t=1 6 30
t=2 8 25
t=3 4 20

我想返回:

datetime    Stock A    Stock B
t=0 100 100
t=1 120 150
t=2 140 125
t=3 80 100

用数学术语来说:Index(i, t) = P(i, t)/P(i, 0)。

我试过了

df_norm =  df[0:] / df[0:1]
print(df_norm)

这给了我一个错误。

edit1:我尝试了选项 3,效果很好(还不能尝试 NaN,但至少它不会为第一个 obs 创建 NaN(由 pctchange 引起))。我还想知道在执行之后,我的日期时间不再是设置的索引,只需重新分配它就可以轻松修复。

现在我正在尝试将它包装在一个函数中,但我认为索引导致了问题(实际上与我的“第一次”尝试相同的错误):

def norming(x):
return x.assign(**x.drop('datetime', 1).pipe(
lambda d: d.div(d.shift().bfill()).cumprod()))

edit2:如果我的日期时间列是一个索引,即

df_norm.set_index(['datetime'], inplace = True)

不过我会得到一个错误,我需要更改什么?

最佳答案

选项 1

df.set_index('datetime').pct_change().fillna(0) \
.add(1).cumprod().mul(100).reset_index()

datetime Stock A Stock B
0 t=0 100.0 100.0
1 t=1 120.0 150.0
2 t=2 160.0 125.0
3 t=3 80.0 100.0

选项 2

def idx_me(a):
a = np.asarray(a)
r = np.append(1, a[1:] / a[:-1])
return r.cumprod() * 100

df.assign(**df.drop('datetime', 1).apply(idx_me))

datetime Stock A Stock B
0 t=0 100.0 100.0
1 t=1 120.0 150.0
2 t=2 160.0 125.0
3 t=3 80.0 100.0

选项 3

df.assign(**df.drop('datetime', 1).pipe(
lambda d: d.div(d.shift().bfill()).cumprod().mul(100)))

datetime Stock A Stock B
0 t=0 100.0 100.0
1 t=1 120.0 150.0
2 t=2 160.0 125.0
3 t=3 80.0 100.0

关于pandas - "Indexing"到起始时间点(指数水平 = 100)的价格序列,带有 pandas 数据框 : P(i, t)/P(i),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49583389/

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