组合单索引数据帧和多索引数据帧的方法,而不需要对单索引数据框架进行多索引



有没有一种干净简单的方法来组合多索引和单索引数据帧?

这里和这里都有类似的问题,但都是老问题,都有"混乱"的解决方案。

我有一个单一的索引数据名称:

df1 = pd.DataFrame({'single': [10,11,12], 'double': [7,8,9]})
single  double
0      10       7
1      11       8
2      12       9

我希望将其组合为一系列多索引数据帧,其中包含具有不同列和子列索引的空列:

df2 = pd.DataFrame(columns = pd.MultiIndex.from_product([['happy'], ['very', 'not_much']]))    
Empty DataFrame
Columns: [(happy, very), (happy, not_much)]
Index: []

然后下一次我将把它添加到上面两个数据帧的组合中,依此类推:

df3 =pd.DataFrame(columns = pd.MultiIndex.from_product([['sad'], ['always', 'never']]))
Empty DataFrame
Columns: [(sad, always), (sad, never)]
Index: []

我尝试了附加和连接,但两者都出现了第三个错误:

TypeError: Expected tuple, got str

最终目标是得到这样的数据帧:

happy              sad  
single   double  very  not_much  always  never
0      10       7
1      11       8
2      12       9

我只需要使用concat,然后对列进行后处理:

resul = pd.concat([df1, df2, df3], axis=1, sort=False)
resul.columns = pd.MultiIndex.from_tuples(
[('', i) if isinstance(i, str) else i for i in resul.columns])

它给出了预期的:

happy             sad      
single double  very not_much always never
0     10      7   NaN      NaN    NaN   NaN
1     11      8   NaN      NaN    NaN   NaN
2     12      9   NaN      NaN    NaN   NaN

最新更新