【问题标题】:pd.concat gets rid of multi-index when axis is set to axis=1当axis设置为axis = 1时,pd.concat摆脱了多索引
【发布时间】:2019-08-02 05:47:44
【问题描述】:

我正在尝试连接具有相同索引但不同多索引列的四个数据帧。

当我使用: df = pd.concat([df_wa, df_avg, df_sum, df_count], sort=False)

然后写入 excel,DataFrame 打印 Multi Index,其中第一个索引在 Excel 的顶行,另一个索引在下面的行。

现金...费用...四月

WA ...计数...平均

但是,轴需要设置为axis=1,这样索引就不会针对每个新数据帧重复。所以我使用:

df = pd.concat([df_wa, df_avg, df_sum, df_count], axis=1, sort=False)

但是当它被转换为元组时,我丢失了多索引。

(free_cash_flow, WA) ... (fees_received, count)....(apr, avg)

我尝试使用关卡、键和 unstack 都没有成功。知道如何取消索引吗?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    如果您使用 df.columns = multidex 值设置多索引,则效果很好。他们只需要具有相同数量的级别

    示例:

    array1 = ['animal', 'animal']
    array2 = ['has wings', 'no wings']
    
    tuples = list(zip(array1, array2))
    col = pd.MultiIndex.from_tuples(tuples)
    
    df = pd.DataFrame([['bird', 'monkey'], ['dragon','horse']])
    df.columns = col
    
    
    array1 = ['foo', 'foo']
    array2 = ['baz', 'bar']
    tuples = list(zip(array1, array2))
    col = pd.MultiIndex.from_tuples(tuples)
    
    df2 = pd.DataFrame([['bird', 'monkey'], ['dragon','horse']])
    df2.columns = col
    
    new_df = pd.concat([df, df2], axis=1)
    print(new_df)
    

    输出:

         animal              foo        
      has wings no wings     baz     bar
    0      bird   monkey    bird  monkey
    1    dragon    horse  dragon   horse
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-19
      • 2016-03-09
      • 2011-12-30
      • 1970-01-01
      • 1970-01-01
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多