首页 > 解决方案 > Pandas 如果行值包含列表中的项目作为子字符串,则将行值保存到不同的数据框

问题描述

如果行值包含列表中的项目作为子字符串,则将行值保存到不同的数据框。

输入数据帧:

index    link
1      https://zeewhois.com/en/
2      https://www.phpfk.de/domain
3      https://www.phpfk.de/de/domain
4      https://laseguridad.online/questions/1040/pued

list=['verizon','zeewhois','idad']

如果 df['link'] 有任何项目 list作为子字符串,我们需要将其放在link不同的新数据框中。

到目前为止,我已经对该link列进行了预处理并购买了这种格式:

index    link
1      httpszeewhoiscomenwww
2      httpswwwphpfkdedomain
3      httpswwwphpfkdededomain
4      httpslaseguridadonlinequestions1040pued

查找哪些行值包含list子字符串 中的项目df["TRUEFALSE"] = df['link'].apply(lambda x: 1 if any(i in x for i in list) else 0)

但我得到了错误:

TypeError: 'in <string>' requires string as left operand, not float

标签: pythonpandas

解决方案


你可以使用 str.contains

list_strings =['verizon','zeewhois','idad']

df.loc[df.link.str.contains('|'.join(list_strings),case=False), 'TRUE_FALSE'] = True



 index             link                                TRUE_FALSE
    1   https://zeewhois.com/en/                        True
    2   https://www.phpfk.de/domain                     NaN
    3   https://www.phpfk.de/de/domain                  NaN
    4   https://laseguridad.online/questions/1040/pued  True

然后只需过滤 True 以获取您的新数据框

new_df = df.loc[df.TRUE_FALSE == True].copy()

index               link                        TRUE_FALSE
1   https://zeewhois.com/en/                        True
4   https://laseguridad.online/questions/1040/pued  True

推荐阅读