【问题标题】:Remove words in each row in a column of dataframe from another list of words in a column of another dataframe从另一个数据框的一列中的另一个单词列表中删除数据框列中每一行中的单词
【发布时间】:2021-02-03 09:43:33
【问题描述】:

我想从每一行的另一个数据框中减去或删除一个数据框中的单词。

这是 pyspark 数据框的主表/列。

+----------+--------------------+
|  event_dt|           cust_text|
+----------+--------------------+
|2020-09-02|hi fine i want to go|
|2020-09-02|i need  a line hold |
|2020-09-02|i have the  60 packs|
|2020-09-02|hello want you teach|

下面是另一个 pyspark 数据框。此数据框中的单词需要从上述主表中的列cust_text 中删除,无论单词出现在每一行中。例如,'want' 将从每行中删除,只要它出现在第一个数据帧中。

+-------+
|column1|
+-------+
|   want|
|because|
|   need|
|  hello|
|      a|
|   have|
|     go|
+-------+

这可以在 pyspark 或 pandas 中完成。我尝试使用 Python、Pyspark、pandas 搜索解决方案,但仍然无法根据单列表从主表中删除单词。

结果应该是这样的:

+----------+--------------------+
|  event_dt|           cust_text|
+----------+--------------------+
|2020-09-02|hi fine i to        |
|2020-09-02|i line hold         |
|2020-09-02|i the 60 packs      |
|2020-09-02|you teach           |
+----------+--------------------+

【问题讨论】:

    标签: python pandas dataframe text pyspark


    【解决方案1】:

    如果你只想删除 df2 对应行中的单词,你可以这样做,但对于大型数据集可能会很慢,因为它只能部分使用快速 C 实现:

    # define your helper function to remove the string
    def remove_string(ser_row):
        return ser_row['cust_text'].replace(ser_row['remove'], '')
    
    # create a temporary column with the string to remove in the first dataframe
    df1['remove']= df2['column1']
    df1= df1.apply(remove_string, axis='columns')
    # drop the temporary column afterwards
    df1.drop(columns=['remove'], inplace=True)
    

    结果如下:

    Out[145]: 
    0        hi fine i  to go
    1    i need   lines hold 
    2    i have the  60 packs
    3           can you teach
    dtype: object
    

    但是,如果您想从 every 列中删除 df2 列中的所有单词,则需要以不同的方式进行操作。不幸的是,str.replace 在这里对常规字符串没有帮助,除非您想为第二个数据帧中的每一行调用它。 所以如果你的第二个数据框不是太大,你可以创建一个正则表达式来使用str.replace

    import re
    replace=re.compile(r'\b(' + ('|'.join(df2['column1'])) + r')\b')
    df1['cust_text'].str.replace(replace, '')
    

    输出是:

    Out[184]: 
    0      hi fine i  to 
    1    i    lines hold 
    2    i  the  60 packs
    3       can you teach
    Name: cust_text, dtype: object
    

    如果您不喜欢剩余的重复空格,您可以执行以下操作:

    df1['cust_text'].str.replace(replace, '').str.replace(re.compile('\s{2,}'), ' ')
    

    加法:如果不仅没有单词的文本是相关的,而且单词本身也是相关的。我们怎样才能得到被替换的单词。这是一种尝试,如果可以识别一个字符,它不会出现在文本中。假设这个字符是@,那么你可以这样做(在没有替换的原始列值上):

    # enclose each keywords in @
    ser_matched= df1['cust_text'].replace({replace: r'@\1@'}, regex=True)
    # now remove the rest of the line, which is unmatched
    # this is the part of the string after the last occurance
    # of a @
    ser_matched= ser_matched.replace({r'^(.*)@.*$': r'\1', '^@': ''}, regex=True)
    # and if you like your keywords to be in a list, rather than a string
    # you can split the string at last
    ser_matched.str.split(r'@+')
    

    【讨论】:

    • 第二个数据帧(df2) 已经完成,需要从第一个数据帧(df1) 中删除。在您的输出中,我看到 'go' 没有从第一个数据帧中删除。
    • 嗨,不客气。我想,您的第二个数据框中的行对应于您的第一个数据框中的行,并且您只想删除属于同一行的字符串。顺便说一句,你是印度人吗?
    • 没有。我想我不能很好地解释。这是我第一次发帖问什么
    • 没问题,我想我有办法了。请稍等。
    • 最后一件事,我想在结果中添加“event_dt”列和相应的行(原样)
    【解决方案2】:

    此解决方案将特定于熊猫。如果我正确理解了您的挑战,您希望从第二个 DataFrame 的 column1 中出现的列 cust_text 中删除所有单词。让我们为相应的 DataFrame 命名:df1df2。你会这样做:

    for i in range(len(df1)):
        sentence = df1.loc[i, "cust_text"]
        for j in range(len(df2)):
            delete_word = df2.loc[j, "column1"]
            if delete_word in sentence:
                sentence = sentence.replace(delete_word, "")
        df1.loc[i, "cust_text"] = sentence
    

    我已将变量分配给这些数据框中的某些数据点(sentencedelete_word),但这只是为了便于理解。如果不这样做,您可以轻松地将这段代码压缩为几行。

    【讨论】:

    • 是的,这就是我想要的。如何定义数据帧的长度?---> for i in range(len(df1)): df1 has 2 columns - event_dt, cust_text.
    • 从技术上讲,DataFrame 应该始终具有相同的行数,而不管它有多少列。将 1 行视为 1 项,其中包含有关数据框中所有特征(也称为列)的信息。也就是说,您可以通过len(dataframe) 访问任何数据帧的长度(即行数)。这是一个内置的python函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 2021-08-16
    • 2021-10-23
    • 2021-11-18
    相关资源
    最近更新 更多