python – 有效地组合多个熊猫系列

我知道我可以使用combine_first合并两个系列:

series1 = pd.Series([1,2,3,4,5],index=['a','b','c','d','e'])
series2 = pd.Series([1,2,3,4,5],index=['f','g','h','i','j'])
series3 = pd.Series([1,2,3,4,5],index=['k','l','m','n','o'])

Combine1 = series1.combine_first(series2)
print(Combine1

输出:

a    1.0
b    2.0
c    3.0
d    4.0
e    5.0
f    1.0
g    2.0
h    3.0
i    4.0
j    5.0
dtype: float64

如果我需要合并3个或更多系列怎么办?

我理解使用以下代码:print(series1 series2 series3)产生:

a   NaN
b   NaN
c   NaN
d   NaN
e   NaN
f   NaN
...
dtype: float64

如果不多次使用combine_first,我可以有效地合并多个系列吗?

谢谢

最佳答案 根据您的编辑,我认为您需要沿第一个轴连接,然后沿同一轴需要一个和.

def combine_multi(ser_list):
    return pd.concat([series1, series2, series3], 1).fillna(0).sum(1)

例A(不同指数)

series1 = pd.Series([1,2,3,4,5],index=['a','b','c','d','e'])
series2 = pd.Series([1,2,3,4,5],index=['f','g','h','i','j'])
series3 = pd.Series([1,2,3,4,5],index=['k','l','m','n','o'])

out = combine_multi([series1, series2, series3])
out

a     5.0
b    12.0
c    15.0
d     3.0
e     4.0
g     6.0
h     7.0
i     8.0
j     9.0
k    10.0
m    12.0
o    14.0
dtype: float64

例B(重叠指数)

series1 = pd.Series([1,2,3,4,5],index=['a','b','c','d','e'])
series2 = pd.Series([1,2,3,4,5],index=['a','b','c','i','j'])
series3 = pd.Series([1,2,3,4,5],index=['k','b','m','d','f'])

out = combine_multi([series1, series2, series3])
out

a    2.0
b    6.0
c    6.0
d    8.0
e    5.0
f    5.0
i    4.0
j    5.0
k    1.0
m    3.0
dtype: float64
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞