【问题标题】:Indexing a series s2 by a series s1 and keep s1 index通过系列 s1 索引系列 s2 并保持 s1 索引
【发布时间】:2016-09-30 19:57:21
【问题描述】:

我想从另外两个系列s1 和s2 构造一个系列s3,如下所示:

In [130]: s1
Out[130]: 
1    b
2    b
3    c
dtype: object

In [131]: s2
Out[131]: 
a    x
b    y
c    z
dtype: object

我希望s3 拥有s1 的索引和s2 的值由s1 的值索引,即:

In [131]: s3
Out[131]: 
1    y
2    y
3    z
dtype: object

到目前为止,我可以通过简单地将s2 索引到s1 来接近:

In [133]: s2.loc[s1]
Out[133]: 
b    y
b    y
c    z
dtype: object

但我不知道如何将索引重置为s1 的索引(它似乎不是reindex 操作)。正在做:

pa.DataFrame(s2.loc[s1], index = s1.index)

也不起作用并给出:

ValueError: 无法从重复的轴重新索引。

【问题讨论】:

    标签: python dictionary pandas indexing


    【解决方案1】:

    使用mapSeriess1s2:

    import pandas as pd
    
    s1 = pd.Series(['b','b','c'], index=[1,2,3])
    s2 = pd.Series(['x','y','z'], index=['a','b','c'])
    
    s3 = s1.map(s2)
    print (s3)
    1    y
    2    y
    3    z
    dtype: object
    

    与map by dict from s2 相同:

    d = s2.to_dict()
    print (d)
    {'a': 'x', 'b': 'y', 'c': 'z'}
    
    s3 = s1.map(d)
    print (s3)
    1    y
    2    y
    3    z
    dtype: object
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多