【问题标题】:How can I filter list by dataframe in python?如何在python中按数据框过滤列表?
【发布时间】:2018-02-11 18:43:13
【问题描述】:

如何在 python 中按数据框过滤列表?

例如,我有列表L = ['a', 'b', 'c'] 和数据框df

Name Value
   a     0
   a     1
   b     2
   d     3

结果应该是['a', 'b']

【问题讨论】:

    标签: python list pandas numpy dataframe


    【解决方案1】:
    a = df.loc[df['Name'].isin(L), 'Name'].unique().tolist()
    print (a)
    ['a', 'b']
    

    或者:

    a = np.intersect1d(L, df['Name']).tolist()
    print (a)
    ['a', 'b']
    

    时间安排

    df = pd.concat([df]*1000).reset_index(drop=True)
    
    L = ['a', 'b', 'c']
    
    #jezrael 1
    In [163]: %timeit (df.loc[df['Name'].isin(L), 'Name'].unique().tolist())
    The slowest run took 5.53 times longer than the fastest. This could mean that an intermediate result is being cached.
    1000 loops, best of 3: 774 µs per loop
    
    #jezrael 2    
    In [164]: %timeit (np.intersect1d(L, df['Name']).tolist())
    1000 loops, best of 3: 1.81 ms per loop
    
    #divakar
    In [165]: %timeit ([i for i in L if i in df.Name.tolist()])
    1000 loops, best of 3: 393 µs per loop
    
    #john galt 1
    In [166]: %timeit (df.query('Name in @L').Name.unique().tolist())
    The slowest run took 5.30 times longer than the fastest. This could mean that an intermediate result is being cached.
    100 loops, best of 3: 2.36 ms per loop
    
    #john galt 2    
    In [167]: %timeit ([x for x in df.Name.unique() if x in L])
    The slowest run took 5.32 times longer than the fastest. This could mean that an intermediate result is being cached.
    10000 loops, best of 3: 182 µs per loop
    

    【讨论】:

    • 我猜想在L 中看到更多的元素,而不仅仅是3 :)
    • 当然,我添加了小数据,因为 OP 说小 df。给我一秒钟
    • @Dmitry - 您的数据的实际大小是多少?你的 L 尺寸是多少?
    • dfL 中大约有 1000 条记录,结果长度约为 30 个字符。但最重要的问题是实际数据如下:df 中的aaaL 中的aaa.z(带有'.z' 扩展名)。所以,我不能使用像[i for i in l if i in df.Name.tolist()]这样的方法。
    【解决方案2】:

    使用query的另一种方式

    In [1470]: df.query('Name in @L').Name.unique().tolist()
    Out[1470]: ['a', 'b']
    

    或者,

    In [1472]: [x for x in df.Name.unique() if x in L]
    Out[1472]: ['a', 'b']
    

    【讨论】:

      【解决方案3】:

      这是一个 -

      [i for i in l if i in df.Name.tolist()]
      

      示例运行 -

      In [303]: df
      Out[303]: 
        Name  Value
      0    a      0
      1    a      1
      2    b      2
      3    d      3
      
      In [304]: l = ['a', 'b', 'c']
      
      In [305]: [i for i in l if i in df.Name.tolist()]
      Out[305]: ['a', 'b']
      

      【讨论】:

      • jezrael's解决方案快吗?
      • @Dmitry 自己测试?还是提供时间数据集?
      • 我没有那么多数据。只是好奇:) 无论如何,谢谢你的回答!
      • 我添加了计时,真的很有趣。
      猜你喜欢
      • 1970-01-01
      • 2018-06-24
      • 2017-12-15
      • 2020-04-13
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 2019-11-27
      • 2020-05-17
      相关资源
      最近更新 更多