首页 > 解决方案 > 使用 pandas 连接多索引列

问题描述

如何连接两个 pandas 数据帧,其中一个数据帧具有多索引列?我需要在最终数据框中保留多索引。

import numpy as np
import pandas as pd

df1_cols = ["a", "b"]
df1_vals = np.random.randint(1, 10, [2, 2])
df1 = pd.DataFrame(data=df1_vals, columns=df1_cols)

df2_cols = pd.MultiIndex.from_tuples([("c", "1"), ("c", "2"), ("d", "1"), ("d", "2")])
df2_vals = np.random.randint(1, 10, [2, 4])
df2 = pd.DataFrame(data=df2_vals, columns=df2_cols)

df = pd.concat([df1, df2], axis=1)

使用pd.concat(),多索引将被压缩。

   a  b  (c, 1)  (c, 2)  (d, 1)  (d, 2)
0  3  7       1       6       1       3
1  6  1       2       7       6       3

标签: pythonpandasconcatenationmulti-index

解决方案


您需要MultiIndex在两个 DataFrame 中用于MultiIndex最终 DataFrame:

df1.columns = pd.MultiIndex.from_product([df1.columns, ['']])
print (df1.columns)
MultiIndex([('a', ''),
            ('b', '')],
           )

df = pd.concat([df1, df2], axis=1)
print (df)
   a  b  c     d   
         1  2  1  2
0  5  6  6  9  7  7
1  1  7  7  7  2  6

推荐阅读