重塑日内大熊猫的每日数据

时间:2018-10-25 19:47:23

标签: python pandas

我有一个看起来像这样的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

如何在熊猫中做到这一点?

2 个答案:

答案 0 :(得分:2)

如果您的索引是 <Switch> <Route exact path="/" component={home} /> </Switch> <Route path="/(.+)" render={() => ( <div> <Switch> <Route path="/home" component={Home} /> <Route path="/test" component={test} /> </Switch> </div> )} /> dtype,请创建一个MultiIndex并调用str

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

答案 1 :(得分:2)

假设您的数据框具有单个级别pivot_table索引,则可以使用熊猫datetime。将datetime分配给单独的变量,然后使用这种方法

date = df.index.date
time = df.index.time
# Use pivot_table to reshape dataframe
df_reshaped = df.pivot_table(index=time, columns=date, values='Last')
df_reshaped

          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