我正在尝试在Python中创建gale-Shapley算法,该算法可以稳定匹配医生和医院.为此,我给每位医生和每家医院随机选择了一个以数字表示的偏好.
由首选项组成的数据框
之后,我创建了一个函数,该函数为每个医院的一位特定医生评分(用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()
导致下表:
数据框由医生的喜好和评分等级组成
因此,排名所代表的医生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()
总结 以上是内存溢出为你收集整理的我想创建新的数据框列循环遍历特定列的行 全部内容,希望文章能够帮你解决我想创建新的数据框列循环遍历特定列的行 所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)