【发布时间】: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