【问题标题】:Remove all words containing '@' from list in DataFrame从 DataFrame 的列表中删除所有包含“@”的单词
【发布时间】:2018-07-03 05:36:45
【问题描述】:

我有一个 DataFrame,其中一列包含单词列表。

>>dataset.head(1)
>>               contain
  0            ["name", "Place", "ect@gtr", "nick"]
  1            ["gf@e", "nobel", "play", "hi"]

我想删除所有包含'@' 的单词。在上面的例子中,我想删除"ect@gtr""gf@e"

【问题讨论】:

  • 你在用pythonpandas吗?

标签: regex python-3.x list pandas dataframe


【解决方案1】:

试试这个

ab= np.column_stack([~df[col].str.contains(r"@") for col in df])
new_df=df.loc[ab.any(axis=1)]
print(new_df)

【讨论】:

    【解决方案2】:

    使用list comprehension 进行过滤,这里不需要正则表达式:

    df =  pd.DataFrame({'contain':[['name', 'Place', 'ect@gtr', 'nick'],
                                   ['gf@e', 'nobel', 'play', 'hi']]})
    print (df)
                            contain
    0  [name, Place, ect@gtr, nick]
    1       [gf@e, nobel, play, hi]
    
    df.contain = df.contain.apply(lambda x: [y for y in x if '@' not in y])
    

    或者:

    df.contain = [[y for y in x if '@' not in y] for x in df.contain]
    
    print (df)
                   contain
    0  [name, Place, nick]
    1    [nobel, play, hi]
    

    编辑:要删除字符串中的值,请添加 splitjoin

    df =  pd.DataFrame({'contain':['name Place ect@gtr nick',"gf@e nobel play hi"]})
    print (df)
    
                       contain
    0  name Place ect@gtr nick
    1       gf@e nobel play hi
    
    df.contain = df.contain.apply(lambda x: ' '.join([y for y in x.split() if '@' not in y]))
    print (df)
               contain
    0  name Place nick
    1    nobel play hi
    

    【讨论】:

    • 它工作了,如果我有一个像“name Place ect@gtr nick”这样的字符串,现在我想删除 ect@gtr?
    • @ImranAhmadGhazali - 你认为["name", "Place", "ect@gtr", "nick"]"name Place ect@gtr nick" 还是["name", "Place", "ect@gtr", "nick"] 就像["name", "Place", "ect@gtr", "name Place ect@gtr nick"] 一样?
    • 不,两者都有区别,实际上,我有一个类似“name Place ect@gtr nick”的字符串。以前我正在更改它的标记,例如 ["name"、"Place"、"ect@gtr"、"nick"]。所以想知道答案
    猜你喜欢
    • 2011-06-13
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 2018-06-15
    • 1970-01-01
    相关资源
    最近更新 更多