我有一个带有DatetimeIndex的数据框:

                          X
timestamp
2013-01-01 00:00:00  0.788500
2013-01-01 00:30:00  0.761525
2013-01-01 01:00:00  0.751850
2013-01-01 01:30:00  0.746445
2013-01-01 02:00:00  0.688677


我正在使用unstack以每半小时间隔将其重塑为列,将日期作为行-如this answer中所建议。

df.index = [df.index.date, df.index.hour + df.index.minute / 60]
df = df['X'].unstack()
df.head()
              0.0       0.5       1.0       1.5       2.0       2.5   \
2013-01-01  0.788500  0.761525  0.751850  0.746445  0.688677  0.652226
2013-01-02  0.799029  0.705590  0.661059  0.627001  0.606560  0.592116
2013-01-03  0.645102  0.597785  0.563410  0.516707  0.495896  0.492416
2013-01-04  0.699592  0.649553  0.598019  0.576290  0.561023  0.537802
2013-01-05  0.782781  0.706697  0.645172  0.627405  0.605972  0.583536


都好。
但是,我现在想对多个数据帧执行相同的过程。最初,我使用2:

for df in [df1,df2]:
        df.index = [df.index.date, df.index.hour + df.index.minute / 60]
        df = df['X'].unstack()


重新编制索引有效,但重新成形不起作用:

df1.head()

                      X
2013-01-01 0.0  0.788500
           0.5  0.761525
           1.0  0.751850
           1.5  0.746445
           2.0  0.688677


我想也许我需要一些等效的inplace,所以未堆叠的数据帧将传递回df1df2

有什么建议么?

最佳答案

问题原因

您需要检查分配在Python中的工作方式。 Brandon Rhodes的talk很有启发性。

当您执行df = df['X'].unstack()时,您将dfdf1的未堆叠版本分配给df2,具体取决于迭代,因此您有2个选择




就地执行,但似乎没有就地unstack
保留另一个对未堆叠版本的引用,并为这些版本分配df1df2


可以使用元组,列表或字典来完成。

提取重塑

最简单的方法是将操作本身提取为单独的方法

def my_reshape(df):
    df_copy = df.copy() # so as to leave the original DataFrame intact
    df_copy.index = [df.index.date, df.index.hour + df.index.minute / 60]
    return df_copy['X'].unstack()


作为元组

df1, df2 = tuple(my_reshape(df) for df in (df1, df2))


有字典的变体

df_dict = {'df1': df1, 'df2': df2}
for key, df in df_dict.items():
    df_dict[key] = my_reshape(df)


然后如果您在dict之外需要它们

df1 = df_dict['df1']
df2 = df_dict['df2']

09-07 05:26
查看更多