python - 将 Pandas 中的两个系列沿着它们的索引组合起来

标签 python pandas series

<分区>

我有两个 pandas 系列。

系列 1:

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

和系列 2:

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

我如何根据 id 组合表格以形成下面的表格?

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

最佳答案

您可以使用 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

注意:如果这些是 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

关于python - 将 Pandas 中的两个系列沿着它们的索引组合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18083187/

相关文章:

python - Django 中的 WordPress 小部件类型功能

python - 使用 numpy 在多个轴上进行 bool 掩码

python - 如何在 Pandas 中对两列进行区分?

python - 如何根据日期时间值创建列?

c++ - 无限级数的并行计算

excel - VBA ChartObject 更改图例中系列的名称

python - 如何根据条件生成随机数

python - Scikit 学习多核 : "AttributeError: StdIn instance has no attribute ' close'"

python - 如何将 DataFrame 写入 postgres 表

python - Pandas:将类别转换为数字