首页 > 解决方案 > 重塑盘中价值熊猫的每日数据

问题描述

我有一个看起来像这样的 DF:

                             Last
1996-02-26 09:31:00     65.750000
1996-02-26 09:32:00     65.890625
1996-02-26 09:33:00           NaN

1996-03-27 09:31:00    266.710000
1996-03-27 09:32:00    266.760000
1996-03-27 09:33:00    266.780000

我想重塑我的数据看起来像这样:

         1996-02-26    1996-03-27
9:31:00   65.75           266.71
9:32:00   65.890625       266.76
9:33:00   NaN             266.78

我怎样才能在熊猫中做到这一点?

标签: pythonpandas

解决方案


如果您的索引是strdtype,请创建一个 MultiIndex 并调用unstack

idx = pd.MultiIndex.from_arrays(zip(*df.index.str.split()))
df = df.set_index(idx)['Last'].unstack(0)

print(df)
          1996-02-26  1996-03-27
09:31:00   65.750000      266.71
09:32:00   65.890625      266.76
09:33:00         NaN      266.78

如果索引值为 的替代解决方案datetimes

idx =  pd.MultiIndex.from_arrays([df.index.time, df.index.floor('D')])
df = df.set_index(idx)['Last'].unstack()

print(df)
          1996-02-26  1996-03-27
09:31:00   65.750000      266.71
09:32:00   65.890625      266.76
09:33:00         NaN      266.78

推荐阅读