gpt4 book ai didi

python - 插入顶行时出现问题

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

我有一个名为 table 的 df,我想插入一个 0 列表作为第一行。

table:
           A B C D
Date
2016-04-21  0.020068  0.027631  0.006116   0.005451
2016-04-22  0.008741  0.006732 -0.013585   0.003863
2016-04-25 -0.020516 -0.020339 -0.007526  -0.010102
2016-04-26  0.051630  0.032790  0.008437   0.015524

我创建了一个函数,不创建长度 = header 数量的 0 列表。

def arr():
arr = []
for i in range(len(list(table()))):
arr.append(0)
return arr

pd.DataFrame([arr()],columns=list(table()))

print(table())

给出错误:

Shape of passed values is (1, 1), indices imply (4, 1)

最佳答案

首先需要创建新的索引值,add new rowlocdf,最后 sort_index :

df.loc[df.index[0] - pd.offsets.DateOffset(days=1)] = 0
df = df.sort_index()
print (df)
A B C D
Date
2016-04-20 0.000000 0.000000 0.000000 0.000000
2016-04-21 0.020068 0.027631 0.006116 0.005451
2016-04-22 0.008741 0.006732 -0.013585 0.003863
2016-04-25 -0.020516 -0.020339 -0.007526 -0.010102
2016-04-26 0.051630 0.032790 0.008437 0.015524

关于python - 插入顶行时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43633910/

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