pandas 沿着它们的索引组合熊猫中的两个系列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18083187/
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-13 21:03:57  来源:igfitidea点击:

Combining two series in pandas along their index

pythonpandasseries

提问by user7289

I have two series in pandas.

我有两个Pandas系列。

series 1:

系列一:

id        count_1
1            3
3           19
4           15
5            5
6            2

and series 2:

和系列2:

id        count_2
1           3
3           1
4           1
5           2
6           1

How do I combine the tables along the ids to form the below?

我如何沿着 id 组合表格以形成下面的表格?

id        count_1    count_2
1            3        3
3           19        1
4           15        1
5            5        2
6            2        1

回答by Andy Hayden

You can use concat:

您可以使用concat

In [11]: s1
Out[11]:
id
1      3
3     19
4     15
5      5
6      2
Name: count_1, dtype: int64

In [12]: s2
Out[12]:
id
1     3
3     1
4     1
5     2
6     1
Name: count_2, dtype: int64

In [13]: pd.concat([s1, s2], axis=1)
Out[13]:
    count_1  count_2
id
1         3        3
3        19        1
4        15        1
5         5        2
6         2        1

Note: if these were DataFrame (rather than Series) you could use merge:

注意:如果这些是 DataFrame(而不是 Series),您可以使用merge

In [21]: df1 = s1.reset_index()

In [22]: s1.reset_index()
Out[22]:
   id  count_1
0   1        3
1   3       19
2   4       15
3   5        5
4   6        2

In [23]: df2 = s2.reset_index()

In [24]: df1.merge(df2)
Out[24]:
   id  count_1  count_2
0   1        3        3
1   3       19        1
2   4       15        1
3   5        5        2
4   6        2        1