【问题标题】:How to go from a flattened dataframe with single-level columns back to a multi-indexed dataframe?如何从具有单级列的扁平化数据框返回到多索引数据框?
【发布时间】:2022-12-30 23:20:48
【问题描述】:

我想从以前带有单级列的扁平化数据框回到多索引数据框。

这是一个例子:

import pandas as pd

# Create a sample dataframe with multi-indexed columns
df = pd.DataFrame({('A', 'a'): [1, 2, 3], ('A', 'b'): [4, 5, 6], ('B', 'a'): [7, 8, 9], ('B', 'b'): [10, 11, 12]})

print(df)

多索引数据框:

   A     B    
   a  b  a   b
0  1  4  7  10
1  2  5  8  11
2  3  6  9  12

比展平:

# Flatten the columns using the to_flat_index() method
df.columns = df.columns.to_flat_index()

print(df)

具有单级列的扁平化数据框:

   (A, a)  (A, b)  (B, a)  (B, b)
0       1       4       7      10
1       2       5       8      11
2       3       6       9      12

如何从具有单级列的扁平化数据框返回到多索引数据框?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    第一个案例

    从上面的示例中获取扁平化数据框:

    # Create a new MultiIndex from the columns tuples names
    new_columns = pd.MultiIndex.from_tuples(df.columns)
    
    # Assign the new MultiIndex to the columns
    df.columns = new_columns
    
    print(df)
    
    

    结果是:

       A     B    
       a  b  a   b
    0  1  4  7  10
    1  2  5  8  11
    2  3  6  9  12
    

    因为df.columns = df.columns.to_flat_index()方法返回的是一个新的单层级的Index对象,这是将多级列名扁平化为元组的结果。

    因此,要从扁平化数据框创建新的多索引数据框,您需要提取原始多索引列名称的元组并将它们传递给pd.MultiIndex.from_tuples 方法。

    第二个案例

    您可能会遇到不同的展平数据帧,如本例所示:

    import pandas as pd
    
    # Create a sample dataframe with multi-indexed columns
    df = pd.DataFrame({('A', 'a'): [1, 2, 3], ('A', 'b'): [4, 5, 6], ('B', 'a'): [7, 8, 9], ('B', 'b'): [10, 11, 12]})
    
    # Flatten the columns
    df.columns = ['_'.join(col) for col in df.columns]
    
    print(df)
    

    结果是:

       A_a  A_b  B_a  B_b
    0    1    4    7   10
    1    2    5    8   11
    2    3    6    9   12
    

    在这种情况下,您可以使用以下代码来获取多索引数据框:

    # Create a new MultiIndex from a list of tuples
    new_columns = pd.MultiIndex.from_tuples([tuple(col.split('_')) for col in df.columns])
    
    # Assign the new MultiIndex to the columns
    df.columns = new_columns
    
    print(df)
    

    结果是:

       A     B    
       a  b  a   b
    0  1  4  7  10
    1  2  5  8  11
    2  3  6  9  12
    

    【讨论】:

      猜你喜欢
      • 2020-12-17
      • 2023-03-23
      • 2019-04-05
      • 2020-02-26
      • 2019-05-29
      • 2014-08-09
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多