【问题标题】:Iterating a list of Pandas dataframes / reshaping dataframe with .unstack使用 .unstack 迭代 Pandas 数据框列表/重塑数据框
【发布时间】:2017-11-05 20:18:01
【问题描述】:

我有一个带有 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 loops pandas dataframe reshape


    【解决方案1】:

    问题原因

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

    当您执行 df = df['X'].unstack() 时,您会将 df1df2 的未堆叠版本分配给 df,具体取决于迭代,因此您有 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)
    

    如果你之后在字典之外需要它们

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 2023-02-04
      • 1970-01-01
      • 2012-12-10
      • 1970-01-01
      • 1970-01-01
      • 2020-04-19
      相关资源
      最近更新 更多