【问题标题】:Can I use regular expressions search or match on a Python Pandas column where each cell is a list of lists?我可以在每个单元格都是列表列表的 Python Pandas 列上使用正则表达式搜索或匹配吗?
【发布时间】:2020-09-10 11:41:31
【问题描述】:

我有一个较大的 CSV 文件(>2,000 行),我已读入 Pandas,并希望根据某个数据列中是否出现特定单词来创建一个新的指示符列。我一直在尝试使用正则表达式搜索,这可能有点矫枉过正,因为这个词总是会被空格分隔,但 DataFrame 的单元格是字符串列表的列表。我尝试过使用双重列表推导进行迭代,但是有错误,而且我也很好奇,作为一个 Python 新手,是否有一个通用的解决方案可以让未指定数量的嵌套列表变平。这是一个示例,我的最终目标是在所选列的单元格中出现'saddle' 一词的行中包含1 的新列,如果没有出现0

我的 DataFrame 是这样的

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

我认为这个错误是它不喜欢接收正则表达式的非字符串(也许是未展平的列表?)。有没有办法在 Pandas 中的列中搜索特定单词(可能使用正则表达式),其中一些单元格是字符串列表,一些是还包含嵌套列表的字符串列表,并且缺少一些单元格,以创建指示列, 1 表示它出现的任何地方(无论它是否嵌套),否则 0

【问题讨论】:

    标签: python regex pandas flatten dummy-variable


    【解决方案1】:

    您可以使用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
    

    希望这会有所帮助!!1

    【讨论】:

    • 非常感谢您的帮助!我需要学习地图。再次感谢!!
    猜你喜欢
    • 1970-01-01
    • 2013-05-12
    • 2010-12-28
    • 1970-01-01
    • 2013-11-02
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    相关资源
    最近更新 更多