[英]Python: concatenate pandas multiindex
我需要生成一个 pd.DataFrame,其中的列由一个列表和一个 Multiindex 对象组成,我需要在用数据填充最终数据帧之前执行此操作。
假设列是['one', 'two']
和从from_product
获得的多from_product
:
import pandas as pd
col_21 = ['day', 'month']
col_22 = ['a', 'b']
mult_2 = pd.MultiIndex.from_product([ col_21, col_22 ])
我想获得如下所示的列列表:
'one' | 'two' | ('day','a') | ('day','b') | ('month','a') | ('month','b')
一种可能的解决方案是使用两个不同且独立的 Multiindex,一个带有虚拟列,均由from_product
生成
col_11 = ['one', 'two']
col_12 = ['']
col_21 = ['day', 'month']
col_22 = ['a', 'b']
mult_1 = pd.MultiIndex.from_product([ col_11, col_12 ])
mult_2 = pd.MultiIndex.from_product([ col_21, col_22 ])
我怎么能做到这一点?
(one, '') | (two, '') | ('day','a') | ('day','b') | ('month','a') | ('month','b')
我尝试了几个简单的解决方案,但每个都给了我不同的错误或错误的结果
mult_1+mult_2 #TypeError: cannot perform __add__ with this index type: MultiIndex
pd.merge #TypeError: Can only merge Series or DataFrame objects, a <class 'list'> was passed
pd.MultiIndex.from_arrays([ mult_1, mult_2 ]) #NotImplementedError: isna is not defined for MultiIndex
谢谢你的建议
如果可能的话,最好是建立MultiIndex in index
按列one
, two
,然后MultiIndex in columns
通过对-所以不混合非多指标与multindex值:
col_21 = ['day', 'month']
col_22 = ['a', 'b']
mult_2 = pd.MultiIndex.from_product([ col_21, col_22 ])
one = range(5)
two = list('ABCDE')
mult_3 = pd.MultiIndex.from_arrays([ one, two], names=['one','two'])
df = pd.DataFrame(0, columns=mult_2, index=mult_3)
print (df)
day month
a b a b
one two
0 A 0 0 0 0
1 B 0 0 0 0
2 C 0 0 0 0
3 D 0 0 0 0
4 E 0 0 0 0
使用Index.append
:
print (mult_1.append(mult_2))
MultiIndex([( 'one', ''),
( 'two', ''),
( 'day', 'a'),
( 'day', 'b'),
('month', 'a'),
('month', 'b')],
)
或带有sort=False
Index.union
:
print (mult_1.union(mult_2, sort=False))
MultiIndex([( 'one', ''),
( 'two', ''),
( 'day', 'a'),
( 'day', 'b'),
('month', 'a'),
('month', 'b')],
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.