首页 > 解决方案 > Python,Pandas:将 Dataframe 与 Dictionary 结合(按条件)

问题描述

大家好,

我有一个与此类似的数据框:

id    |    name    |    personnelNumber
1     |    abcd    |    00013
2     |    efgh    |    00142
19    |    abcd    |    00013
84    |    abcd    |    00013
103   |    efgh    |    00142
117   |    mnop    |    00087

我也有随机值的字典和我的数据框中的“personnelNumber”:

{'00013': 41, '00087': 725, '00142': 19}

我的问题:有没有办法根据匹配的“personnelNumber”将值添加到新列中?我想收到这样的东西:

id    |    name    |    personnelNumber    |    value
1     |    abcd    |    00013              |    41
2     |    efgh    |    00142              |    19
19    |    abcd    |    00013              |    41
84    |    abcd    |    00013              |    41
103   |    efgh    |    00142              |    19
117   |    mnop    |    00087              |    725

感谢所有的建议和帮助!

标签: pythonpandasdictionary

解决方案


假设personnelNumber是类型string(因为前导零),您可以使用pd.Series.map

d = {'00013': 41, '00087': 725, '00142': 19}

df['value'] = df.personnelNumber.map(d)
df

出去:

    id  name personnelNumber  value
0    1  abcd           00013     41
1    2  efgh           00142     19
2   19  abcd           00013     41
3   84  abcd           00013     41
4  103  efgh           00142     19
5  117  mnop           00087    725

推荐阅读