Python 迭代数据帧列表/使用.unstack重塑数据帧

Python 迭代数据帧列表/使用.unstack重塑数据帧,python,loops,pandas,dataframe,reshape,Python,Loops,Pandas,Dataframe,Reshape,我有一个带有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对其进行

我有一个带有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
对其进行重塑,以半小时的间隔作为列,日期作为行-如中所建议的

一切都好。 但是我现在想对一些数据帧执行相同的过程。最初,我使用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
,以便将未堆叠的数据帧传递回
df1
df2

有什么建议吗?

问题原因 您需要检查赋值在Python中是如何工作的。布兰登·罗德斯的这篇文章很有启发性

执行
df=df['X'].unstack()
时,根据迭代情况,将
df1
df2
的未堆叠版本分配给
df
,因此您有两个选项

解决方案
  • 原地踏步,但似乎没有原地踏步

  • 保留对未标记版本的另一个引用,并将
    df1
    df2
    分配给这些版本

这可以通过元组、列表或dict来完成

提取整形图像 最简单的方法是将操作本身提取到一个单独的方法中

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 = df_dict['df1']
df2 = df_dict['df2']
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)
df1 = df_dict['df1']
df2 = df_dict['df2']