问题描述
我需要熊猫码来计算匹配记录的百分比。 假设我有两列Hotel_name和Property_name,并且总记录为100和30条记录都匹配,那么匹配记录的百分比应为30%。
解决方法
如果在两个列上都设置了索引,则可以进行外部联接,然后在某些必需的列上计算空值。
示例:
x = [['hotel1','property1'],['hotel2','property2'],['hotel3','property3'],['hotel9','property9']]
y = [['hotel1',['hotel4','property4'],['hotel5','property5']]
df1 = pd.DataFrame(x,columns=['hotel_name','property_name'])
df2 = pd.DataFrame(y,'property_name'])
df1['flag'] = 1
df2['flag'] = 1
df1.set_index(['hotel_name','property_name'],inplace=True)
df2.set_index(['hotel_name',inplace=True)
ans = df1.join(df2,how='outer',lsuffix='x',rsuffix='y',sort=True)
print("Percent Match in X is: ",100*(1-len(ans[ans.flagx.isna()]) / len(ans)))
print("Percent Match in Y is: ",100*(1-len(ans[ans.flagy.isna()]) / len(ans)))
print(ans)
结果:
Percent Match in X is: 66.66666666666667
Percent Match in Y is: 83.33333333333334
flagx flagy
hotel_name property_name
hotel1 property1 1.0 1.0
hotel2 property2 1.0 1.0
hotel3 property3 1.0 1.0
hotel4 property4 NaN 1.0
hotel5 property5 NaN 1.0
hotel9 property9 1.0 NaN