[英]Join pandas series of multIndex
我怎样才能联接Series A
multiindexed由(A, B)
与Series B
通过索引A
?
Currently the only way is to bring the indices to a common footing -- eg move the B
level of the series_A
MultiIndex to a column so that both series_A
and series_B
are indexed only by A
: 当前,唯一的方法是使索引处于一个共同的基础上-例如,将
series_A
MultiIndex的B
级别移至一列,以便series_A
和series_B
都仅由A
进行索引:
import pandas as pd
series_A = pd.Series(1, index=pd.MultiIndex.from_product([['A1', 'A4'],['B1','B2']], names=['A','B']), name='series_A')
# A B
# A1 B1 1
# B2 1
# A4 B1 1
# B2 1
# Name: series_A, dtype: int64
series_B = pd.Series(2, index=pd.Index(['A1', 'A2', 'A3'], name='A'), name='series_B')
# A
# A1 2
# A2 2
# A3 2
# Name: series_B, dtype: int64
tmp = series_A.to_frame().reset_index('B')
result = tmp.join(series_B, how='outer').set_index('B', append=True)
print(result)
yields 产量
series_A series_B
A B
A1 B1 1.0 2.0
B2 1.0 2.0
A2 NaN NaN 2.0
A3 NaN NaN 2.0
A4 B1 1.0 NaN
B2 1.0 NaN
Another way to join them would be to unstack the B
level from series_A
: 加入它们的另一种方法是从
series_A
B
级:
In [215]: series_A.unstack('B').join(series_B, how='outer')
Out[215]:
B1 B2 series_B
A
A1 1.0 1.0 2.0
A2 NaN NaN 2.0
A3 NaN NaN 2.0
A4 1.0 1.0 NaN
unstack
moves the B
index level to the column index. unstack
将B
索引级别移到列索引。 Thus the theme is the same (bring the indices to a common footing), though the result is different. 因此,主题是相同的(将索引带到相同的位置),尽管结果不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.