你如何在 Pandas 中合并 2 系列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42514444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:05:50  来源:igfitidea点击:

How do you Merge 2 Series in Pandas

pythonpandasseries

提问by Suminda Sirinath S. Dharmasena

I have the following:

我有以下几点:

s1 = pd.Series([1, 2], index=['A', 'B'])

s2 = pd.Series([3, 4], index=['C', 'D'])

I want to combine s1and s2to create s3which is:

我想结合s1s2创建s3

s3 = pd.Series([1, 2, 3, 4], index=['A', 'B', 'C', 'D'])

NB: There is no index overlap

注意:没有索引重叠

采纳答案by clocker

Solution from @EdChum works well, but numpy stacking is faster when you don't need to worry about index alignment.

@EdChum 的解决方案效果很好,但是当您不需要担心索引对齐时,numpy 堆叠会更快。

In [18]: pd.DataFrame( np.hstack((s1.values, s2.values))  , index=np.hstack((s1.index.values, s2.index.values)))
Out[18]: 
   0
A  1
B  2
C  3
D  4

In [19]: %timeit pd.concat([s1, s2])

1000 loops, best of 3: 1.31 ms per loop

In [21]: %timeit pd.DataFrame( np.hstack((s1.values, s2.values)  ), index=np.hstack((s1.index.values, s2.index.values)))

10000 loops, best of 3: 214 μs per loop

回答by elcombato

You can use concat(), it automatically executes an outer join:

您可以使用concat(),它会自动执行外连接:

pd.concat([s1, s2])

result:

结果:

A    1
B    2
C    3
D    4
dtype: int64

回答by Yama? Alican I??k

If there is no index overlap, you could just use the append function defined for series with the default values

如果没有索引重叠,您可以使用为系列定义的带有默认值的 append 函数

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.append.html#pandas.Series.append

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.append.html#pandas.Series.append

s1.append(s2) 

should return:

应该返回:

A    1
B    2
C    3
D    4
dtype: int64