如何在另一个数据框上通过类似vlookup的过程创建新的pandas列

问题描述 投票:0回答:1

我有一个看起来像这样的数据框。它将用于使用两个分类变量映射值。也许把它转换成字典会更好。 Index, and Column names represent possible values taken by two categorical variables in another data-frame

第二个数据框非常大,屏幕截图如下所示。我想从分类变量中获取值,以基于第一个数据框创建一个新属性(列)。

例如...

FICO_cat为(700,720)且OrigLTV_cat为(75,80)的行将获得值5。

FICO_cat为(700,720)且OrigLTV_cat为(85,90)的行将获得值6。

有没有一种有效的方法来做到这一点?

enter image description here

pandas dictionary categorical-data
1个回答
1
投票

如果您的列标签是FICO_cat值,而您的IndexOrigLTV_cat,这应该有效:

给定数据帧df

         780+  (740,780)  (720,740)
(60,70)     3          3          3
(70,75)     4          5          4
(75,80)     3          1          2

做:

df = df.unstack().reset_index()
df.rename(columns = {'level_0' : 'FICOCat', 'level_1' : 'OrigLTV', 0 : 'value'}, inplace = True)

输出:

     FICOCat  OrigLTV  value
0       780+  (60,70)      3
1       780+  (70,75)      4
2       780+  (75,80)      3
3  (740,780)  (60,70)      3
4  (740,780)  (70,75)      5
5  (740,780)  (75,80)      1
6  (720,740)  (60,70)      3
7  (720,740)  (70,75)      4
8  (720,740)  (75,80)      2
© www.soinside.com 2019 - 2024. All rights reserved.