【问题标题】:How to check if dataframe column contains multiple sets of strings and output a row for each set it contains如何检查数据框列是否包含多组字符串并为其包含的每个集合输出一行
【发布时间】:2020-11-19 14:43:13
【问题描述】:

我有 2 个数据框 - 1 个数据表,另一个用于此类主题

df_Data = pd.DataFrame({'ID':['123','456','789','100','200'],
                    'Names':['the dog is Red and blue','Cat is Pink','animal is cyan','pet is BLUE','i am green']})

df_Topics = pd.DataFrame({'Blue':['blue','cyan','aqua'],
                    'Red':['red','pinnk','fuscia','crimson']})

我正在寻找使用主题列表来查找这些关键字中是否有任何关键字在 df_Data 中,然后创建一个新表,其中在数据中找到主题,如下所示:

ID   Topics
123   Blue
123   Red
456   Red
789   Blue
100   Blue

【问题讨论】:

  • 您的第二个数据帧不可重现。你能测试并修复它吗?

标签: python-3.x pandas list dataframe


【解决方案1】:

您可以使用正则表达式extractNames 列中的所有关键字,然后map 回到主颜色。因此,您需要 df_topics 的不同数据结构,它更适合作为 dict

df_Topics = {'Blue': ['blue','cyan','aqua'], 'Red': ['red','pink','fuscia','crimson']}

s = {color: k for k, v in df_Topics.items() for color in v}

print (s)

{'blue': 'Blue', 'cyan': 'Blue', 'aqua': 'Blue', 'red': 'Red', 'pink': 'Red', 'fuscia': 'Red', 'crimson': 'Red'}

现在使用str.extractall获取所有关键字,分配回一列,最后map返回:

df_Data = (df_Data.assign(Topics=df_Data["Names"].str.extractall(f'({"|".join(s)})', flags=re.I)
                          .groupby(level=0).agg(list)).explode("Topics"))

print (df_Data.assign(Topics=df_Data["Topics"].str.lower().map(s)))

    ID                    Names Topics
0  123  the dog is Red and blue    Red
0  123  the dog is Red and blue   Blue
1  456              Cat is Pink    Red
2  789           animal is cyan   Blue
3  100              pet is BLUE   Blue
4  200               i am green    NaN

【讨论】:

  • 谢谢,这很好用。我打算从 csv 开始,所以我使用此代码以您开始的格式读取 csv: reader = csv.DictReader(open(file_location_kw)) df_Topics = {} for row in reader: for column, value in row.items(): # 考虑 Python 2 的 .iteritems() if value !='': df_Topics.setdefault(column, []).append(value) print(df_Topics)
【解决方案2】:

谢谢!这真的很好用。我打算从 csv 开始,所以我使用此代码以您开始的格式读取 csv:

reader = csv.DictReader(open('file.csv'))

df_Topics = {}
for row in reader:
    for column, value in row.items():  # consider .iteritems() for Python 2
        if value !='': 
            df_Topics.setdefault(column, []).append(value)
print(df_Topics)

【讨论】:

    猜你喜欢
    • 2021-04-06
    • 2018-08-27
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    相关资源
    最近更新 更多