[英]selecting values from a pandas dataframe based on row and column labels stored in a different dataframe
I have two dataframes: the first contains rating and tenor per ID 我有两个数据框:第一个包含等级和每个ID的期限
df1 =
ID RATING TENOR
1234 BBB 2.0
2345 BB+ 1.5
3456 BBB- 1.0
The ID is the index column. ID是索引列。
In the second dataframe df2 I have a matrix of rating as index and tenor as column names. 在第二个数据帧df2中,我有一个等级矩阵作为索引,而男高音作为列名。
0.5 1.0 1.5 2.0
BBB+ 0.000750 0.001500 0.002651 0.003800
BBB 0.001201 0.002400 0.003751 0.005100
BBB- 0.001401 0.002800 0.006256 0.009700
BB+ 0.002854 0.005700 0.009106 0.012500
BB 0.004058 0.008100 0.014470 0.020800
BB- 0.006723 0.013400 0.024108 0.034700
B+ 0.011567 0.023000 0.043005 0.062600
B 0.033874 0.066600 0.086257 0.105500
B- 0.048475 0.094600 0.124649 0.153700
now I would like to select the value that corresponds to the rating and the tenor of each id in df1 and add it to a new column in df1. 现在,我想选择与df1中每个ID的等级和年期相对应的值,并将其添加到df1中的新列中。 So the result should look like: 因此结果应如下所示:
ID RATING TENOR PD
1234 BBB 2.0 0.005100
2345 BB+ 1.5 0.009106
3456 BBB- 1.0 0.002800
I tried 我试过了
df1['PD'] = df2.loc[df1.RATING, df1.TENOR].values df1 ['PD'] = df2.loc [df1.RATING,df1.TENOR] .values
but this doesn't work. 但这不起作用。 Thanks for your help. 谢谢你的帮助。
df1['PD'] = df2.lookup(df1.RATING,df1.TENOR.astype(str))
Output: 输出:
RATING TENOR PD
ID
1234 BBB 2.0 0.005100
2345 BB+ 1.5 0.009106
3456 BBB- 1.0 0.002800
Note: I had to use astype because my dtypes didn't match in my df2.columns and df1.TENOR. 注意:我必须使用astype,因为df2.columns和df1.TENOR中的dtypes不匹配。 You'll have to check this you might not need to astype depending on your datatypes. 您必须检查一下,您可能不需要根据您的数据类型进行astype。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.