简体   繁体   English

有没有办法通过python中的dict直接迭代一个系列?

[英]Is there a way to directly iterate a series through a dict in python?

Trying to figure out the best way to iterate a series through a dictionary in pandas.试图找出通过 Pandas 中的字典迭代系列的最佳方法。 Here is my MRE:这是我的 MRE:

s1 = pd.Series(['a','b','c','d'])

d = {'a':1, 'b':2, 'c':3, 'd':4}

what I want to do is create s2 such that我想要做的是创建 s2 这样

s2 = pd.Series([1,2,3,4])

by processing s1 through d.通过处理 s1 到 d。 So far, the best way I can think of is到目前为止,我能想到的最好方法是

s2 = pd.Series([d[item] for item in list(s1)])

I am aware of the option to do我知道可以做的选择

s2 = pd.Series(d.values())

but the actual problem I am trying to solve would require passing the series through a dictionary.但我试图解决的实际问题需要通过字典传递系列。

You can use map :您可以使用map

s1 = pd.Series(['a','b','c','d'])
d = {'a':1, 'b':2, 'c':3, 'd':4}
s2 = s1.map(d)

output:输出:

0    1
1    2
2    3
3    4

Try with replace尝试replace

s2 = s1.replace(d)
s2
Out[17]: 
0    1
1    2
2    3
3    4
dtype: int64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM