Python 将数据实时附加到空数据帧

Python 将数据实时附加到空数据帧,python,pandas,python-datetime,Python,Pandas,Python Datetime,我想实时向空数据框添加一些数据: import pandas as pd import time df = pd.DataFrame(columns=['time', 'price']) # this is a simple example # but in my code, I have more #

我想实时向空数据框添加一些数据:

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
...

如何将数据添加到这样的数据框中?

您正在使用
df[t]
将数据框索引到列t中。我想你应该按行索引

不过,从外观上看,似乎一个系列可能更适合,因为您正在按时间索引进行更新

import pandas as pd
import time

series = pd.Series()

for i in range(5):
    time.sleep(2)
    t = pd.datetime.now()
    series[t] = 5 + i

print series


import pandas as pd
import time
在需要数据帧的情况下,可以使用
df.ix[行索引]
追加数据帧:

df = pd.DataFrame(columns = ['col1', 'col2'])

for i in range(5):
    time.sleep(2)
    t = pd.datetime.now() # Generate row index
    df.ix[t] = {'col1': 5 + i, 'col2': 20 + i}


print df
考虑使用pandas函数将循环数据列表迁移到dataframe:

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

谢谢,但是我真的需要一个DataFrame(因为我有几个列)来添加一个例子。使用索引附加一行。这是不可能的,因为实际上我的
for
循环比
范围(5)
长得多(持续时间为1天),我需要能够访问循环内更新的数据帧。我在原始问题的代码中添加了一些注释。请参阅更新。仍然是相同的概念,但不是在循环中添加到列表,然后在循环外批量添加到df,而是每次迭代都会在循环中添加到df。更新是否满足您的需要?如果我的解决方案对你有帮助,请接受。