【问题标题】:filtering a dataframe if the length of the word inside the series > 3如果系列中单词的长度> 3,则过滤数据框
【发布时间】:2021-09-18 20:25:44
【问题描述】:

社区!到目前为止,我非常感谢我在学习 python 的过程中得到的所有支持!

我得到了以下数据框:

d = {'name': ['john', 'mary', 'james'], 'area':[['IT', 'Resources', 'Admin'], ['Software', 'ITS', 'Programming'], ['Teaching', 'Research', 'KS']]}
df = pd.DataFrame(data=d)

我的目标是:

换句话说,如果'area'列的列表中的单词长度> 3,则将其删除。

我正在尝试这样的事情,但我真的被卡住了

处理这种情况的最佳方法是什么?

再次感谢!!

【问题讨论】:

    标签: python pandas dataframe filtering


    【解决方案1】:

    将.map 与列表理解结合起来:

    df['area'] = df['area'].map(lambda x: [e for e in x if len(e)>3])
    
    0         [Resources, Admin]
    1    [Software, Programming]
    2       [Teaching, Research]
    

    解释:

    x = ["Software", "ABC", "Programming"]
    # return e for every element in x but only if length of element is larger than 3
    [e for e in x if len(e)>3]
    

    【讨论】:

      【解决方案2】:

      在构建数据框之前。

      一种简单有效的方法是创建一个新的 key: "area" 列表,其中仅包含长度大于 3 的字符串。例如:

      d = {'name': ['john', 'mary', 'james'], 'area':['IT', 'Resources', 'Admin'], ['Software', 'ITS', 'Programming'], ['Teaching', 'Research', 'KS']]}
      
      # Retrieving the areas from d.
      area_list = d['area']
      
      # Copying all values, whose length is larger than 3, in a new list.
      filtered_area_list = [a in area_list if len(3) > 3]
      
      # Replacing the old list in the dictionary with the new one.
      d['area'] = filtered_area_list
      
      # Creating the dataframe.
      df = pd.DataFrame(data=d)
      

      构建数据框之后。

      如果您的数据在数据框中,那么您可以使用 "map" 函数:

      df['area'] = df['area'].map(lambda a: [e for e in a if len(e) > 3])
      

      【讨论】:

      • 感谢您的回复!!我真的很感谢你的支持!!谢谢!
      【解决方案3】:

      您可以expand all your lists、filter on str length,然后通过aggregating 使用list 将它们放回列表中:

      df = df.explode("area")
      df = df[df["area"].str.len() > 3].groupby("name", as_index=False).agg(list)
      #     name                     area
      # 0  james     [Teaching, Research]
      # 1   john       [Resources, Admin]
      # 2   mary  [Software, Programming]
      

      【讨论】:

      • 它也有效,亚历克斯!非常感谢!非常感谢您的时间和关注!
      • @VictorCastro 我要补充一点,通常最好不要将数据保存在数据框中的列表中。这称为长格式数据,它使过滤/分组更容易
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 2013-12-22
      • 2019-10-08
      • 2012-08-18
      • 1970-01-01
      相关资源
      最近更新 更多