我可以在每个单元格都是列表的Python列上使用正则表达式搜索或匹配吗?

2024-04-23 11:52:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Pandas中读取了一个较大的CSV文件(>;2000行),希望根据某个数据列中是否出现特定的单词来创建一个新的指示符列。我一直在尝试使用正则表达式搜索,这可能有些过分,因为单词总是以空格分隔,但数据帧的单元格是字符串列表。我尝试过使用双列表理解进行迭代,但是有一些错误,作为一个Python新手,我也很好奇,是否有一个通用的解决方案可以将数量不确定的嵌套列表展平。下面是一个示例,其中我的最终目标是一个新列,在所选列的单元格中,单词'saddle'出现在任何位置的行中有1,如果没有0

我的数据框看起来像这样

import pandas as pd
import numpy as np

cycling = pd.DataFrame(
    {
        'qty' : [1,0,2,1,1],
        'item' : ['frame','frame',np.nan,'order including a saddle and other things','brake'],
        'desc' : [np.nan,['bike','wheel'],['bike',['tire','tube']],['saddle',['seatpost','bag']],['bike','brakes']]
    }
)

Here is the DataFrame

我可以使用以下代码搜索item列以实现我的目标(效率和其他建议非常欢迎!!):

cycling['saddle1'] = [int(bool(re.search(r"saddle",x))) for x in cycling['item'].replace(np.nan,'missing')]

我的原始数据集缺少要在指示符列中解析为0的值;否则我不在乎他们。上面的代码对于每个单元格the fourth row is correctly identified中包含字符串的列非常有效,但是当单元格包含列表或列表(如desc列)时,我无法修改它。我试过:

cycling['saddle2'] = [int(bool(re.search(r"saddle",x))) for y in cycling['desc'].replace(np.nan,'missing') for x in y]

但是我得到了以下错误

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-45-4c72cdaa87a4> in <module>()
----> 1 cycling['saddle2'] = [int(bool(re.search(r"saddle",x))) for y in cycling['desc'].replace(np.nan,'missing') for x in y]
      2 cycling.head()

1 frames
/usr/lib/python3.6/re.py in search(pattern, string, flags)
    180     """Scan through string looking for a match to the pattern, returning
    181     a match object, or None if no match was found."""
--> 182     return _compile(pattern, flags).search(string)
    183 
    184 def sub(pattern, repl, string, count=0, flags=0):

TypeError: expected string or bytes-like object

我认为错误在于它不喜欢接收regex的非字符串(可能是未格式化的列表?)。有没有一种方法可以在Pandas中搜索一列特定的单词(可能使用regex),其中有些单元格是字符串列表,有些单元格是也包含嵌套列表的字符串列表,有些单元格丢失,从而创建一个指示符列,在它出现的任何位置(无论是否嵌套)都有一个1,否则就有一个0


Tags: 数据字符串inre列表forsearchstring
1条回答
网友
1楼 · 发布于 2024-04-23 11:52:53

您可以使用map,而不是运行for循环(这很慢)。您可以将列表转换为str以调用正则表达式。例如:

import pandas as pd
import numpy as np
import re

cycling = pd.DataFrame(
    {
        'qty' : [1,0,2,1,1],
        'item' : ['frame','frame',np.nan,'order including a saddle and other things','brake'],
        'desc' : [np.nan,['bike','wheel'],['bike',['tire','tube']],['saddle',['seatpost','bag']],['bike','brakes']]
    }
)
cycling['saddle1'] = cycling['item'].replace(np.nan,'missing').map(lambda x :int(bool(re.search(r"saddle",x))))
cycling['saddle2'] = cycling['desc'].replace(np.nan,'missing').map(lambda x :int(bool(re.search(r"saddle",str(x)))))

cycling

希望这有帮助!!一,

相关问题 更多 >