连接 Series 与元组作为 multiindex 中的索引结果

Concatenate Series with tuples as index results in multiindex

我有两个以元组为索引的系列。这两个系列有一些共同的指标,但不是全部。

当我尝试(并排)连接它们时,生成的数据帧具有多索引,而不是元组。如何让生成的数据帧将时间序列索引的并集作为元组作为索引?

(注意:如果两个系列具有完全相同的元组索引,则生成的数据帧也具有元组作为索引)

import pandas as pd
import numpy as np
from string import ascii_lowercase
from string import ascii_uppercase

ts1 = pd.Series(np.random.rand(5), index = [(ascii_lowercase[ix], ascii_uppercase[ix]) for ix in range(5)])
ts2 = pd.Series(np.random.rand(6), index = [(ascii_lowercase[ix], ascii_uppercase[ix]) for ix in range(6)])

df = pd.concat([ts1, ts2], axis = 1)

ts1
Out[39]: 
(a, A)    0.417022
(b, B)    0.720324
(c, C)    0.000114
(d, D)    0.302333
(e, E)    0.146756

df
Out[38]: 
            0         1
a A  0.417022  0.092339
b B  0.720324  0.186260
c C  0.000114  0.345561
d D  0.302333  0.396767
e E  0.146756  0.538817
f F       NaN  0.419195

df.index
Out[29]: 
MultiIndex(levels=[[u'a', u'b', u'c', u'd', u'e', u'f', u'g', u'h', u'i', u'j', u'k', u'l', u'm', u'n', u'o', u'p', u'q', u'r', u's', u't'], [u'A', u'B', u'C', u'D', u'E', u'F', u'G', u'H', u'I', u'J', u'K', u'L', u'M', u'N', u'O', u'P', u'Q', u'R', u'S', u'T']],
           labels=[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])

方法一
join

ts1.to_frame('ts1').join(ts2.to_frame('ts2'), how='outer')

             ts1       ts2
(a, A)  0.174646  0.180041
(b, B)  0.674112  0.246414
(c, C)  0.101622  0.142237
(d, D)  0.079782  0.097109
(e, E)  0.613248  0.389077
(f, F)       NaN  0.226176

方法二
重新分配您的 index

df = pd.concat([ts1, ts2], axis=1)
df.index = df.index.to_series()
df

               0         1
(a, A)  0.174646  0.180041
(b, B)  0.674112  0.246414
(c, C)  0.101622  0.142237
(d, D)  0.079782  0.097109
(e, E)  0.613248  0.389077
(f, F)       NaN  0.226176

方法三
merge

ts1.reset_index().merge(
    ts2.reset_index(), on=['index'], how='outer').set_index('index')

             0_x       0_y
index                     
(a, A)  0.174646  0.180041
(b, B)  0.674112  0.246414
(c, C)  0.101622  0.142237
(d, D)  0.079782  0.097109
(e, E)  0.613248  0.389077
(f, F)       NaN  0.226176

解决方案是添加 values 以将 index 转换为 tupleslist:

df = pd.concat([ts1, ts2], axis = 1, keys=['ts1','ts2'])
df.index = df.index.values
print (df)
             ts1       ts2
(a, A)  0.407183  0.866382
(b, B)  0.069167  0.975522
(c, C)  0.697429  0.855803
(d, D)  0.453543  0.011714
(e, E)  0.722056  0.359978
(f, F)       NaN  0.729991