【问题标题】:Inserting/Adding another column level to pandas dataframe [duplicate]向熊猫数据框插入/添加另一个列级别[重复]
【发布时间】:2021-05-05 16:21:47
【问题描述】:

我需要在pd.DataFrame 的列索引中插入/添加另一个级别。我目前的解决方案是基于来回转换索引。但是,我不认为这是最 Pythonic 的解决方案。我正在寻求改进。

import numpy as np
import pandas as pd

data = np.random.randint(0, 100, [3,3])
df = pd.DataFrame(data=data, columns= ["col0_L0", "col1_L0", "col2_L0"])
df.columns.name = "L0"

print(df)

L0  col0_L0  col1_L0  col2_L0
0        86       14       89
1        69       91       80
2        49        5       28

# That are the new columns headers
col_l1 = ["col0_L1", "col1_L1", "col2_L1"]

# Here's my solution
df = df.T
df.insert(0, "L1", col_l1)
df = df.set_index("L1", drop=True, append=True).T

print(df)

L0 col0_L0 col1_L0 col2_L0
L1 col0_L1 col1_L1 col2_L1
0       86      14      89
1       69      91      80
2       49       5      28

【问题讨论】:

  • df.columns = [df.columns, col_l1] ??
  • 我期待一个单行,但我没想到它如此简单和直观;-)

标签: python pandas multi-index


【解决方案1】:

试试pd.MultiIndex.from_arrays

df.columns = pd.MultiIndex.from_arrays([col_l1,df.columns],names=['L0','L1'])

L0 col0_L0 col1_L0 col2_L0
L1 col0_L1 col1_L1 col2_L1
0       14      58      52
1       92      21      16
2       39      86      93
print(df.columns)

 MultiIndex([('col0_L0', 'col0_L1'),
            ('col1_L0', 'col1_L1'),
            ('col2_L0', 'col2_L1')],
           names=['L0', 'L1'])

【讨论】:

  • 我喜欢这个解决方案的地方是我可以直接传递关卡名称。
  • @Andi pandas 有一个非常灵活的 API :) 快乐编码。
猜你喜欢
  • 2019-09-14
  • 2021-06-27
  • 2021-06-11
  • 2020-04-30
  • 1970-01-01
  • 2022-01-23
  • 2022-11-18
  • 2021-10-06
相关资源
最近更新 更多