2 回答

TA贡献1951条经验 获得超3个赞
使用merge与左连接,对于非存在值id使用fillna,并最后创建Series的set_index具有to_dict:
source = pd.DataFrame({'id':[111111,222222,666666,888888], 'username':['aa','ss','dd','ff']})
data_code = pd.DataFrame({'code':[0]*4, 0:['ss','dd','rr','yy']})
FofToID = (data_code.merge(source, left_on=0, right_on='username', how='left')
.fillna({'id': int(random.random()*10000000)})
.set_index(0)['id']
.to_dict()
)
print (FofToID)
{'ss': 222222.0, 'dd': 666666.0, 'rr': 367044.0, 'yy': 367044.0}

TA贡献1796条经验 获得超10个赞
这是我得到的最终解决方案:
for i in range(len(uniqueIDs)):
if uniqueIDs[i] in list(source["username"]):
FofToID[uniqueIDs[i]]= int(source[source["username"]==uniqueIDs[i]]["id"])
else:
FofToID[uniqueIDs[i]]= int(random.random()*10000000)
输出看起来像那样
添加回答
举报