python - 通过系列 s1 索引系列 s2 并保留 s1 索引

标签 python dictionary pandas indexing

我想从另外两个系列 s1s2 构造一个系列 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 的索引以及由 s1 的值索引的 s2 的值>,即:

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

到目前为止,我只需通过 s1 索引 s2 就可以接近:

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: cannot reindex from a duplicate axis.

最佳答案

使用map 系列 s1 by s2:

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 相同来自 s2dict:

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

关于python - 通过系列 s1 索引系列 s2 并保留 s1 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37568830/

相关文章:

python - 计算每组的滚动总和

python - 使用埃拉托斯特尼筛法给定范围内的素数

python - 如何有效地将大字符串从 Python 传递到 C++ 扩展方法?

java - 将 Java LinkedHashMap 转换为 C++ std::map

python - 无法使用 OpenShift 安装 Pandas

python - 如何访问一个类的子类作为属性?

c# - 使用字符串表达式 c# 将列表转换为字典

python - 子数据帧的子数据帧

python - 如何对数组函数进行排序

python - 跨行排名