根据元素长度在python数据框中删除字符串的元素

时间:2021-01-15 14:21:57

标签: python dataframe nlp string-length

我有一个由 13 列和 60000 行组成的 python 数据框,其中一列名为“文本”(类型对象)包含很长的文本单元格:

    Text    ID  AI  BI  GH  JB  EQ  HE  EN  MA  WE  WR
2585    obstetric gynaecologicaladmissions owing abor...    2585    0   0   0   0   0   1   0   0   0   0
507     graphic illustration process flow help organiz...   507     0   0   0   0   0   0   0   0   1   0

某些行中的某些词被粘贴(例如在第一个数据框行中:gynaecologicaladmissions),为了摆脱这种情况,我想删除整个数据集中的所有这些案例。 我想删除,对于“文本”列中的每一行,所有超过13个字符的单词

我试过这行代码:

res.loc[res['Text'].str.len() < 13]

但它只提供两个空行。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

让我们举一个示例数据帧

df

    text
0   obstetric gynaecologicaladmissions owing
1   graphic illustration process flow help
2   process flow help
3   illustrationprocess flow

由于您必须检查单词长度,因此您必须按分隔符(在本例中为空格)拆分每个字符串并循环遍历数组并包含长度<= 13 的单词。循环遍历数组中的每个您可以使用 apply

def func(x):
    res = list()
    for word in x:
        if len(word) <= 13:
            res.append(word)
    return " ".join(res)
    
df['text'] = df['text'].str.split().apply(func)
df
    
     text
0   obstetric owing
1   graphic illustration process flow help
2   process flow help
3   flow