gpt4 book ai didi

pandas - 将系列与元组连接作为索引会产生多索引

转载 作者:行者123 更新时间:2023-12-02 05:34:17 25 4
gpt4 key购买 nike

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

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

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

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]])

最佳答案

方法 1
加入

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

方法 2
重新分配您的索引

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

方法3
合并

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

关于pandas - 将系列与元组连接作为索引会产生多索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41633021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com