将 Pandas 数据帧转换为带前缀的 cols,而不是 MultiIndex

Ben*_*bey 5 python pandas

我有一个类似于以下内容的时间序列数据框:

ts = pd.DataFrame([['Jan 2000','WidgetCo',0.5, 2], ['Jan 2000','GadgetCo',0.3, 3], ['Jan 2000','SnazzyCo',0.2, 4],
          ['Feb 2000','WidgetCo',0.4, 2], ['Feb 2000','GadgetCo',0.5, 2.5], ['Feb 2000','SnazzyCo',0.1, 4],
          ], columns=['month','company','share','price'])
Run Code Online (Sandbox Code Playgroud)

看起来像:

  month   company  share  price
0  Jan 2000  WidgetCo    0.5    2.0
1  Jan 2000  GadgetCo    0.3    3.0
2  Jan 2000  SnazzyCo    0.2    4.0
3  Feb 2000  WidgetCo    0.4    2.0
4  Feb 2000  GadgetCo    0.5    2.5
5  Feb 2000  SnazzyCo    0.1    4.0
Run Code Online (Sandbox Code Playgroud)

我可以像这样旋转这个表:

pd.pivot_table(ts,index='month', columns='company')
Run Code Online (Sandbox Code Playgroud)

这让我:

            share                      price                  
company  GadgetCo SnazzyCo WidgetCo GadgetCo SnazzyCo WidgetCo
month                                                         
Feb 2000      0.5      0.1      0.4      2.5        4        2
Jan 2000      0.3      0.2      0.5      3.0        4        2
Run Code Online (Sandbox Code Playgroud)

这就是我想要的,除了我需要折叠MultiIndex以便company用作前缀shareprice像这样:

          WidgetCo_share  WidgetCo_price  GadgetCo_share  GadgetCo_price   ...
month                                                                      
Jan 2000             0.5               2             0.3             3.0   
Feb 2000             0.4               2             0.5             2.5   
Run Code Online (Sandbox Code Playgroud)

我想出了这个函数来做到这一点,但它似乎是一个糟糕的解决方案:

def pivot_table_to_flat(df, column, index):
    res = df.set_index(index)
    cols = res.drop(column, axis=1).columns.values
    resulting_cols = []
    for prefix in res[column].unique():
        for col in cols:
            new_col_name = prefix + '_' + col
            res[new_col_name] = res[res[column] == prefix][col]
            resulting_cols.append(new_col_name)

    return res[resulting_cols]

pivot_table_to_flat(ts, index='month', column='company')
Run Code Online (Sandbox Code Playgroud)

有什么更好的方法来完成一个枢轴导致带有前缀而不是 a 的列MultiIndex

Ben*_*bey 1

我想到了。使用上的数据MultiIndex可以得到一个非常干净的解决方案:

def flatten_multi_index(df):
    mi = df.columns
    suffixes, prefixes = mi.levels
    col_names = [prefixes[i_p] + '_' + suffixes[i_s] for (i_s, i_p) in zip(*mi.labels)]
    df.columns = col_names
    return df

flatten_multi_index(pd.pivot_table(ts,index='month', columns='company'))
Run Code Online (Sandbox Code Playgroud)

上面的版本仅处理 2D MultiIndex,但如果需要的话可以进行推广。