【问题标题】:Check if a string is present in multiple lists检查一个字符串是否存在于多个列表中
【发布时间】:2021-07-07 17:10:08
【问题描述】:

我正在尝试根据包含数据集不同对象名称的字符串对数据集进行分类。

数据集由 df['Name']、df['Category'] 和 df['Sub_Category'] 3 列组成,Category 和 Sub_Category 列为空。

对于每一行,如果对象的名称在列表之一中至少包含一个单词,我想检查不同的单词列表。基于此第一次检查,我想为类别列分配一个值。如果它在 2 个不同的列表中找到超过 1 个单词,我想将 2 个值归因于类别列中的对象。

此外,我希望能够识别在哪个列表中检查了哪个单词,以便为 sub_category 列分配一个值。

到目前为止,我只用一个列表就可以做到这一点,但我无法确定检查了哪个单词并且代码运行时间很长。

这是我的代码(我在其中添加了一个在我的数据集中找到的名称示例作为 df['Name']):

import pandas as pd
import numpy as np

df['Name'] = ['vitrine murale vintage','commode ancienne', 'lustre antique', 'solex', 'sculpture médievale', 'jante voiture', 'lit et matelas', 'turbine moteur']

furniture_check = ['canape', 'chaise', 'buffet','table','commode','lit']
vehicle_check = ['solex','voiture','moto','scooter']
art_check = ['tableau','scuplture', 'tapisserie']
    for idx, row in df.iterrows():
        for c in furniture_check:
            if c in row['Name']:
                df.loc[idx, 'Category'] = 'Meubles'

任何帮助将不胜感激

【问题讨论】:

    标签: python pandas list numpy


    【解决方案1】:

    这是一种扩展列表、合并它们并重新组合它们的方法。

    df = pd.DataFrame({"name":['vitrine murale vintage','commode ancienne', 'lustre antique', 'solex', 'sculpture médievale', 'jante voiture', 'lit et matelas', 'turbine moteur']})
    furniture_check = ['canape', 'chaise', 'buffet','table','commode','lit']
    vehicle_check = ['solex','voiture','moto','scooter']
    art_check = ['tableau','scuplture', 'tapisserie']
    
    # put categories into a dataframe
    dfcat = pd.DataFrame([{"category":"furniture","values":furniture_check},
                 {"category":"vechile","values":vehicle_check},
                 {"category":"art","values":art_check}])
    
    # turn apace delimited "name" column into a list
    dfcatlist = (df.assign(name=df["name"].apply(lambda x: x.split(" ")))
                  # explode list so it can be used as join.  reset_index() to keep a copy of index of original DF
     .explode("name").reset_index()
                  # merge exploded names on both side
     .merge(dfcat.explode("values"), left_on="name", right_on="values")
                  # where there are multiple categoryies, make it a list
     .groupby("index", as_index=False).agg({"category":lambda s: list(s)})
                  # but original index back...
     .set_index("index")
    )
    
    # simple join and have names and list of associated categories
    df.join(dfcatlist)
    
    
    name category
    0 vitrine murale vintage nan
    1 commode ancienne ['furniture']
    2 lustre antique nan
    3 solex ['vechile']
    4 sculpture médievale nan
    5 jante voiture ['vechile']
    6 lit et matelas ['furniture']
    7 turbine moteur nan

    【讨论】:

      猜你喜欢
      • 2011-03-24
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      相关资源
      最近更新 更多