python - 熊猫找到最接近个人资料的行
问题描述
我有一个充满配置文件的文件,如下所示:
profile_id colA colB colC colD
1 1 20 50 63
2 1 20 65 38
3 8 5 3 4
4 98 1 878 4
...
我有另一个 CSV,其中包含我想从中查找配置文件的结果:
col value score
colA 1 85
colA 1 856
colA 8 200000
colB 1 2356
colC 878 99999
colD 4 2
...
我想提取value
每个colX
得分最高的文件,并在前一个文件中找到它与哪个 profile_id 相关联。
我所做的是工作:
profiles = pd.read_csv("profiles.csv", sep="\t", index_col=False)
df = pd.read_csv("results.csv", sep="\t", index_col=False)
found_col = set(df["col"])
good_profile = profiles.copy()
for col in profiles.columns:
if col == "profile_id":
continue
elif col not in found_col:
print(f"{col} not found")
else:
value = int(df.loc[df[df["col"] == col]["score"].idxmax()].value)
good_profile = good_profile[good_profile[col] == value]
print(good_profile)
这给了我想要的结果,但我首先为第一列提取一个子集,然后为第二列提取该子集的一个子集,等等......
很酷的一点是,当我错过一些很棒的专栏时,我也会得到一个结果。
我想知道是否有办法让它做得更好,而不必使用在前一个子集上创建子集。
解决方案
这是我的尝试:
# extract the id with max scores
new_df = df2.loc[df2.groupby('col').score.idxmax(), ['col','value']]
# merge
new_df.merge(df1.melt(id_vars='profile_id', var_name='col'),
on=['col','value'],
how='left')
输出:
col value profile_id
0 colA 8 3
1 colB 1 4
2 colC 878 4
3 colD 4 3
4 colD 4 4
推荐阅读
- schema.org - 如何在适当的饮食字段中定义多种饮食限制?
- lstm - 从前一行预测新行
- git - 如何使用 GitLab 在服务器端触发 git 钩子
- xamarin.forms - Web 服务调用已停止处理
- database - 我的 H2/C3PO/Hibernate 设置似乎没有保留准备好的语句?
- ios - 基本视图占用过多 CPU
- html - 拖动时退出禁止光标
- netsuite - ReferenceError - 未定义上下文 (Netsuite)
- java - Gradle.properties 未传递到我的 Java 应用程序
- windows - 为什么 signtool.exe 以管理员身份运行时只能找到证书?