【问题标题】:Use DataFrame values inside .loc[]在 .loc[] 中使用 DataFrame 值
【发布时间】:2021-11-06 21:37:09
【问题描述】:

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

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

还有这样一个DataFrame:

idx match_id type_name second
1 101 Pass 2400
2 101 Shot 2450
3 101 Match_end 2500
4 102 Pass 2700
5 102 Match_end 2600
6 103 Match_end 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 循环的方法。

谢谢

【问题讨论】:

    标签: python pandas optimization coding-style computer-science


    【解决方案1】:

    如果您将字典设为数据框 (df1),则可以通过使用 merge() 连接数据框来进行管理。

    df1 = pd.DataFrame({'match_id':[101, 102, 103], 'second':[2500, 2700, 2000]})
    df2 = pd.DataFrame({'match_id':[101, 101, 101, 102, 102, 103], 'type_name': ['Pass', 'Shot', 'Match_end', 'Pass', 'Match_end', 'Match_end'], 'second':[2400, 2450, 2500, 2700, 2600, 2000]})
    

    只取 df2 中 type_name == 'Match_end' 的行,因为您对其他行不感兴趣。然后删除该 type_name 列,因为以后不需要它。

    df2 = df2.loc[df2.type_name == 'Match_end']
    df2.drop('type_name', axis=1, inplace=True)
    

    合并两个数据框,你就得到了你想要的列表。

    df = df1.merge(df2)
    print(df.match_id.tolist())
    
    [101, 103]
    

    【讨论】:

      【解决方案2】:

      使用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]
      

      【讨论】:

        猜你喜欢
        • 2019-12-16
        • 1970-01-01
        • 2015-02-14
        • 2020-12-28
        • 2018-02-08
        • 2014-05-04
        • 2020-09-05
        • 2019-05-26
        • 1970-01-01
        相关资源
        最近更新 更多