gpt4 book ai didi

python - 将行追加到数据框时遇到困难

转载 作者:太空宇宙 更新时间:2023-11-03 15:19:28 24 4
gpt4 key购买 nike

我期待应用一个涉及 2 个 dfs 的函数:

df1:         A B C D E
12/2/2001 3 4 2 3 4
12/3/2001 5 5 5 4 6
12/4/2001 9 8 7 1 1

df_new = pd.DataFrame().reindex_like(df1)
df_new.loc[df_new.index[0]-pd.offsets.DateOffset(days=1)]=0
df_nuevo=df_new.sort_index()

for i in range(1,len(df_nuevo)):
row=((df1.iloc[:i])*0.55)*((df_nuevo.iloc[:i-1])*0.45)
df_nuevo.append(row)
print(df_nuevo)

我期望的输出是df_nuevo,其中填充了附加行。实际上被 NaN 填充。有人可以帮忙吗?谢谢 。

这是当前输出:

             A    B   C   D   E
12/1/2001 0 0 0 0 0
12/2/2001 NaN NaN NaN NaN NaN
12/3/2001 NaN NaN NaN NaN NaN
12/4/2001 NaN NaN NaN NaN NaN

这个想法是,在有 NaN 的地方出现代码部分中指定的公式的结果:行

最佳答案

如果您只是尝试根据 df1df2 的先前值迭代填写 df2 的行,则可以简单地重新转换您的公式(至少是您最初以伪代码给出的方式)将是:

# create all-zeros df2 same shape as df1
df2 = df1.copy()
df2.loc[:,:] = 0

# iteratively compute df2
for i in range(len(df1)):
df2.iloc[i] = df1.iloc[i] * .55 + df2.iloc[i-1] * .45

对于上面给定的示例,df2 的结果将是:

查看通过循环更新的值可能会很有启发:

i: 0
df1.iloc[i].values: array([ 3., 4., 2., 3., 4.])
df2.iloc[i - 1].values: array([ 0., 0., 0., 0., 0.])
resulting df2.iloc[i].values: array([ 1.65, 2.2 , 1.1 , 1.65, 2.2 ])

i: 1
df1.iloc[i].values: array([ 5., 5., 5., 4., 6.])
df2.iloc[i - 1].values: array([ 1.65, 2.2 , 1.1 , 1.65, 2.2 ])
resulting df2.iloc[i].values: array([ 3.4925, 3.74 , 3.245 , 2.9425, 4.29 ])

i: 2
df1.iloc[i].values: array([ 9., 8., 7., 1., 1.])
df2.iloc[i - 1].values: array([ 3.4925, 3.74 , 3.245 , 2.9425, 4.29 ])
resulting df2.iloc[i].values: array([ 6.521625, 6.083 , 5.31025 , 1.874125, 2.4805 ])

关于python - 将行追加到数据框时遇到困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43637635/

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