加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

我想创建新的数据框列循环遍历特定列的行

发布时间:2020-12-17 17:36:00 所属栏目:Python 来源:网络整理
导读:我正在尝试在Python中创建Gale-Shapley算法,该算法可以稳定匹配医生和医院.为此,我给每位医生和每家医院随机选择了一个以数字表示的偏好. 由首选项组成的数据框 之后,我创建了一个函数,该函数为每个医院的一位特定医生评分(用ID表示),然后对该评分进行排名,

我正在尝试在Python中创建Gale-Shapley算法,该算法可以稳定匹配医生和医院.为此,我给每位医生和每家医院随机选择了一个以数字表示的偏好.

由首选项组成的数据框

enter image description here

之后,我创建了一个函数,该函数为每个医院的一位特定医生评分(用ID表示),然后对该评分进行排名,从而创建了两个新列.在对比赛进行评分时,我采用了偏好之间差异的绝对值,其中绝对值越小越好.这是第一位医生的公式:

  doctors_sorted_by_preference['Rating of Hospital by Doctor 1']=abs(doctors_sorted_by_preference['Preference Doctor'].iloc[0]-doctors_sorted_by_preference['Preference Hospital'])
    doctors_sorted_by_preference['Rank of Hospital by Doctor 1']=doctors_sorted_by_preference["Rating of Hospital by Doctor 1"].rank()

导致下表:
数据框由医生的喜好和评分等级组成

enter image description here

因此,排名所代表的医生1比所有其他医院都更喜欢第一医院.

现在,我想通过创建一个循环(为每个医生创建两个新列并将它们添加到我的数据框)来为每个不同的医生重复此功能,但是我不知道该怎么做.我可以为所有10位不同的医生键入相同的功能,但是如果我将数据集增加到包括1000名医生和医院,这将变得不可能,必须有更好的方法…
这与医生2的功能相同:

doctors_sorted_by_preference['Rating of Hospital by Doctor 2']=abs(doctors_sorted_by_preference['Preference Doctor'].iloc[1]-doctors_sorted_by_preference['Preference Hospital'])
    doctors_sorted_by_preference['Rank of Hospital by Doctor 2']=doctors_sorted_by_preference["Rating of Hospital by Doctor 2"].rank()

先感谢您!

最佳答案
您还可以将值附加到列表中,然后将其写入数据框.如果您的数据集很大,则追加到列表中会更快.

为了便于查看,我将dataframe命名为df:

for i in range(len(df['Preference Doctor'])):
    list1= []
    for j in df['Preference Hospital']:
         list1.append(abs(df['Preference Doctor'].iloc[i]-j))
    df['Rating of Hospital by Doctor_' +str(i+1)] = pd.DataFrame(list1)
    df['Rank of Hospital by Doctor_' +str(i+1)] = df['Rating of Hospital by Doctor_' 
                                                         +str(i+1)].rank()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读