【问题标题】:How to filter a dataframe based on the values present in the list in the rows of a column in Python?如何根据 Python 中列的行中列表中存在的值过滤数据框?
【发布时间】:2016-10-28 04:51:20
【问题描述】:

我有一个如下所示的数据框:

   business_id  stars  categories
0  abcd         4.0    ['Nightlife']
1  abcd1        3.5    ['Pizza', 'Restaurants']
2  abcd2        4.5    ['Groceries', 'Food']

我想根据类别列中的值过滤数据框。我的数据框有大约 400 000 行,我只想要其中包含“食物”或“餐厅”类别的行。

我尝试了很多方法,包括:

def foodie(x):
    for row in x.itertuples():
        if 'Food' in row[3] or 'Restaurant' in row[3]:
            return x

df = df.apply(foodie, axis=1)

但这显然是一个非常非常糟糕的方法,因为我在 400 000 行上使用了 itertuples,而我的系统继续处理无限长的时间。

我还尝试在df[df['categories']] 中使用列表推导。但不能,因为它们都像df[df['stars']==4.0] 一样过滤。甚至我看到的所有apply() 方法都是针对在其列中具有单个值的列实现的。

那么,如何使用相当快的迭代行实现对我的数据框进行子集化,同时仅选择那些在其类别中具有“食物”或“餐厅”的行?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以在类别列上使用apply 方法并检查每个元素是否包含FoodRestaurants,据此创建子集的逻辑索引数组:

    df.loc[df.categories.apply(lambda cat: 'Food' in cat or 'Restaurants' in cat)]
    
    #     business_id             categories      stars
    # 1         abcd1   [Pizza, Restaurants]        3.5
    # 2         abcd2      [Groceries, Food]        4.5
    

    【讨论】:

      【解决方案2】:

      只是另一个想法。保留字符串而不是列表对象。

      In [2]: import pandas as pd
      
      In [3]: data = {'business_id':['abcd','abcd1','abcd2'],'stars':    [4.0,3.5,4.5],'categories':[['Nightlife'],['Pizza', 'Restaurants'],['Groceries', 'Food']]}
      # convert list to string with join() method
      In [15]: df.categories = df.categories.apply(",".join)
      
      In [16]: df 
      Out[16]: 
        business_id         categories  stars
      0        abcd          Nightlife    4.0
      1       abcd1  Pizza,Restaurants    3.5
      2       abcd2     Groceries,Food    4.5
      
      In [26]: df.categories.str.contains('Food')
      Out[26]: 
      0    False
      1    False
      2     True
      Name: categories, dtype: bool
      

      【讨论】:

        猜你喜欢
        • 2020-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-22
        • 2018-08-19
        • 2020-08-16
        • 2020-07-01
        • 1970-01-01
        相关资源
        最近更新 更多