我有一个完整的配置文件,如下所示:
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)
这给了我想要的结果,但是我首先为第一列提取一个子集,然后为第二个提取一个子集,依此类推...
很棒的事情是,当我错过一些很棒的列时,我也会得到结果。
我想知道是否有一种方法可以使它做得更好,而不必用来在先前的子集上创建子集。
答案 0 :(得分:0)
这是我的尝试:
# 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