【问题标题】:Combining two series in pandas along their index [duplicate]沿索引组合熊猫中的两个系列[重复]
【发布时间】:2013-08-07 15:17:42
【问题描述】:

我有两个熊猫系列。

系列一:

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

【问题讨论】:

    标签: python pandas series


    【解决方案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
    

    【讨论】:

    • 谢谢你 - 在你的第一个例子中,第 1 列中的 'id' 位于 'count_1' 和 'count_2' 列标题下方的行中 - 让它们都在同一行中只是按照你的第二个例子?
    • 您可以使用reset_index,它将索引移动到其中一列。
    • @user7289 即pd.concat([s1, s2], axis=1).reset_index()
    • 谢谢安迪,cmets 中的最后一种方法有效...我似乎无法让合并工作...现在排序:)
    • 按其索引合并不重叠索引的 2 个系列怎么样?
    猜你喜欢
    • 2014-10-20
    • 2021-12-07
    • 2019-05-27
    • 1970-01-01
    • 2016-04-23
    • 2013-08-06
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多