gpt4 book ai didi

python - 将数据实时附加到一个空的 pandas DataFrame

转载 作者:太空宇宙 更新时间:2023-11-04 10:17:26 25 4
gpt4 key购买 nike

我想实时向一个空的 DataFrame 添加一些数据:

import pandas as pd
import time

df = pd.DataFrame(columns=['time', 'price']) # this is a simple example
# but in my code, I have more
# columns: 'volume', etc.
for i in range(5): # here it lasts one day in my real use case
time.sleep(2)
t = pd.datetime.now()
df[t] = 5 + i
# here I need to have access to the latest updates of df

print df

输出是:

Empty DataFrame  
Columns: [time, price, 2015-12-27 01:55:29.812000, 2015-12-27 01:55:31.812000, 2015-12-27 01:55:33.812000, 2015-12-27 01:55:35.812000, 2015-12-27 01:55:37.812000]
Index: []

而我想要:

time                                price
2015-12-27 01:55:29.812000 5
2015-12-27 01:55:31.812000 6
2015-12-27 01:55:33.812000 7
...

如何像这样将数据附加到 DataFrame?

最佳答案

考虑使用 pandas 的 append()将循环数据列表迁移到数据框的功能:

df = pd.DataFrame(columns=['time', 'price'])

for i in range(5):
time.sleep(2)
t = pd.datetime.now()
df = df.append(pd.DataFrame({'time': [t],
'price': [5 + i]}))
print df

关于python - 将数据实时附加到一个空的 pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34476705/

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