我使用Pandas与Altair做一些图表。在将DataFrame传递给Altair之前,我希望选择重新采样时间序列数据。我有这个工作,但它创建了一个Altair不能使用的层次数据框对象,因此我试图将数据展平为原始格式。我已经尝试了很多看似几乎解决这个问题的事情,但我无法做到这一点。
初始数据是一个csv,其中包含一系列包含新闻术语的术语,分数和时间戳的行:
james comey,0.00,1524207600
congress,0.00,1524207600
meme,0.17,1524207600
video,0.38,1524207600
barbara bush,2.01,1524207600
trump,2.98,1524207600
...
james comey,0.00,1524211200
congress,0.00,1524211200
meme,0.17,1524211200
video,0.51,1524211200
barbara bush,2.01,1524211200
然后用pandas解析:
import pandas as pd
from datetime import datetime
def dateparse(timestamp):
return datetime.fromtimestamp(int(timestamp))
data = pd.read_csv("data.csv",
parse_dates=[2],
date_parser=dateparse,
names=["term", "score", "timestamp"],
header=None)
从那里我们进行重新采样:
x = data.groupby(['term']).resample('24h', on='timestamp').mean()
这会产生:
score
term timestamp
barbara bush 2018-04-20 2.499167
2018-04-21 5.109167
2018-04-22 4.030000
2018-04-23 1.518333
2018-04-24 1.120000
congress 2018-04-20 0.035000
2018-04-21 0.005833
2018-04-22 0.046667
2018-04-23 0.028333
2018-04-24 0.000000
...
到目前为止看起来不错。 (排序?我认为score
是唯一的列,但数据看起来几乎正确。)现在我想要的另一件事是重新安排它,以便它重新进入原始格式,如:
term timestamp score
barbara bush 2018-04-20 2.499167
barbara bush 2018-04-21 5.109167
barbara bush 2018-04-22 4.030000
barbara bush 2018-04-23 1.518333
barbara bush 2018-04-24 1.120000
congress 2018-04-20 0.035000
congress 2018-04-21 0.005833
congress 2018-04-22 0.046667
我尝试过拆卸,融化,旋转,swap_level / reorder_level(看起来差不多好!)并且在文档中找到的任何其他东西附近诅咒,但我没有太多运气。
思考?