如何在 pandas0 中将其他数据帧中的数字分数添加或替换到数据帧

How to add or replace numeric score from other dataframe to a dataframe in pandas0

提问人:user3685918 提问时间:11/2/2023 更新时间:11/2/2023 访问量:39

问:

我想将其他数据帧中的数字分数添加或替换到数据帧中。

例如,一个数据框写入了信用评级列,并希望添加或替换如下所示的数字分数。

我可以通过 一遍又一遍地构建它,但是有没有更简单或更快的方法?pd.merge


import pandas as pd


df = pd.DataFrame( { 'name' : ['ABC'],
                    'Moodys' :['Aa3'],
                    'SNP' : ['AA'],
                    'Fitch' : ['A']})

credit_socre = {10 : ['AAA', 'Aaa'],
                 9 : ['AA+', 'Aa1'],
                 8 : ['AA', 'Aa2'],
                 7 : ['AA-', 'Aa3'],
                 6 : ['A+', 'A1'],
                 5 : ['A', 'A2'],
                 4 : ['A-', 'A3'],
                 3 : ['BBB+', 'Baa1'],
                 2 : ['BBB', 'Baa2'],
                 1 : ['BBB-', 'Baa3'],
                -1 : ['BB+', 'Ba1'],
                -2 : ['BB', 'Ba2'],
                -3 : ['BB-', 'Ba3'],
                -4 : ['B+', 'B1'],
                -5 : ['B', 'B2'],
                -6 : ['B-', 'B3']}



credit_score2 = pd.DataFrame(credit_socre).transpose().reset_index().rename(columns={'index': 'score', 0 : 'SNP', 1: 'Moodys'})
credit_score2['Fitch'] = credit_score2['SNP']


# >> df
#   name Moodys SNP Fitch
# 0  ABC    Aa3  AA     A


df2 = df.merge(credit_score2, on=['Moodys'], how='left')
df3 = df2.merge(credit_score2, left_on=['Fitch_x'], right_on=['Fitch'], how='left')
df4 = df3.merge(credit_score2, left_on=['SNP_x'], right_on=['SNP'], how='left')

# What I want :
# >> df
#   name Moodys SNP Fitch  Moodys_score   Fitch_score   SNP_score   
# 0  ABC    Aa3  AA     A             7             5           8

```
熊猫 合并

评论


答:

1赞 Panda Kim 11/2/2023 #1

法典

使用 和 use 创建映射器。credit_scorereplace

更换后,concat.

m = {i : key for key, val in credit_score.items() for i in val}
pd.concat([df, df.loc[:, 'Moodys':].replace(m).add_suffix('_score')], axis=1)

输出:

    name    Moodys  SNP Fitch   Moodys_score    SNP_score   Fitch_score
0   ABC     Aa3     AA  A       7               8           5

&您的示例代码有错别字。它需要修复。(credit_socre-> credit_score)