首页 > 解决方案 > 在 .loc[] 中使用 DataFrame 值

问题描述

我想以这种方式过滤 DataFrame,基于字典值。

dict = { 
           101 : 2500,
           102 : 2700,
           103 : 2000,
}

和一个这样的DataFrame:

编号 match_id 类型名称 第二
1 101 经过 2400
2 101 射击 2450
3 101 比赛结束 2500
4 102 经过 2700
5 102 比赛结束 2600
6 103 比赛结束 2000

我想要一行代码返回match_id值,其中type_name==Match_endsecond等于字典中的值,其中键具有相同的 match_id 值。

在这种情况下,我想返回这个列表:[101,103]

因为,在 DataFrame 内部,第 3 行和第 6 行遵守条件(5 否,因为它的second值与 不同dict.get(102))。

我尝试使用此代码但没有成功,因为loc我无法使用相对索引:

list = list(
           df.loc[
               (df["type_name"]=="Match_end")
               & (df["second"] == dict.get(df["match_id"]))
           ]["match_id"].values
       )

我需要第二个条件中的一些东西来帮助我根据match_id每行的值使用字典。

是否有人建议做这件事(有或没有loc)?

NB我知道如何在“match_id”上使用 FOR CICLE 来做到这一点,但我正在寻找一种不使用 FOR 循环的方法。

谢谢

标签: pythonpandasoptimizationcoding-stylecomputer-science

解决方案


按列使用Series.map和比较:second

d = {  101 : 2500,102 : 2700, 103 : 2000}

print (df['match_id'].map(d))
0    2500
1    2500
2    2500
3    2700
4    2700
5    2000
Name: match_id, dtype: int64

L = df.loc[df['match_id'].map(d).eq(df['second']) & 
           (df["type_name"]=="Match_end"), 'match_id'].tolist()
print (L)
[101, 103]

推荐阅读