如何使用其中一列作为引用来匹配两列?

2024-09-26 22:52:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一些分析,发现了一个特殊的模式,现在我正在尝试做一些预测。 我有一个数据集,可以预测学生在童年发生过一定数量事故的评分。 我的预测矩阵是这样的:

   A
   injuries      ratings  
         0            5
         1            4.89
         2            4.34
         3            3.99 
         4            3.89
         5            3.77 

我的数据集如下所示:

B

siblings income injuries total_scoldings_from father
     3       12000   4             09
     4       34000   5             22
     1       23400   3             12
     3       24330   1              1
     0       12000   1             12 

现在我想创建一个列名predictions,它基本上匹配从AB的条目并返回

siblings income injuries total_scoldings_from_father predictions
     3       12000   4             09                    3.89
     4       34000   5             22                    3.77
     1       23400   3             12                    3.99
     3       24330   1             1                     4.89
     0       12000   1             12                    4.89

请帮忙

也建议一个标题,因为我缺乏一切重要的未来参考


Tags: 数据from数量模式矩阵评分学生total
1条回答
网友
1楼 · 发布于 2024-09-26 22:52:54

如果映射的所有值都在数据帧A中,则可以使用^{}

B['predictions'] = B['injuries'].map(A.set_index('injuries')['ratings'])
print (B)
   siblings  income  injuries  total_scoldings_from_father  predictions
0         3   12000         4                            9         3.89
1         4   34000         5                           22         3.77
2         1   23400         3                           12         3.99
3         3   24330         1                            1         4.89
4         0   12000         1                           12         4.89

使用^{}的另一种解决方案:

C = pd.merge(B,A)
print (C)
   siblings  income  injuries  total_scoldings_from_father  ratings
0         3   12000         4                            9     3.89
1         4   34000         5                           22     3.77
2         1   23400         3                           12     3.99
3         3   24330         1                            1     4.89
4         0   12000         1                           12     4.89

相关问题 更多 >

    热门问题