首页 > 解决方案 > 如何从熊猫列中的字符串中删除空格

问题描述

我需要删除 pandas df 列中的空格。我的数据如下所示:

industry            magazine
Home                "Goodhousekeeping.com"; "Prevention.com";
Fashion             "Cosmopolitan"; " Elle"; "Vogue"
Fashion             " Vogue"; "Elle"

下面是我的代码:

# split magazine column values, create a new column in df 
df['magazine_list'] = dfl['magazine'].str.split(';')

# stip the first whitespace from strings
df.magazine_list = df.magazine_list.str.lstrip()

这将返回所有 NaN,我也尝试过:

df.magazine = df.magazine.str.lstrip()

这也没有删除空格。

标签: pythonpandasdataframesplit

解决方案


Jezrael 提供了一个很好的解决方案。知道 pandas 具有类似操作的字符串访问器而不需要列表推导是很有用的。通常,列表推导更快,但根据使用情况,使用 pandas 内置函数可能更具可读性或更易于编码。

df['magazine'] = (
    df['magazine']
    .str.replace(' ', '', regex=False)
    .str.replace('"', '', regex=False)
    .str.strip(';')
    .str.split(';')
)

输出

  industry                                magazine
0     Home  [Goodhousekeeping.com, Prevention.com]
1  Fashion             [Cosmopolitan, Elle, Vogue]
2  Fashion                           [Vogue, Elle]

推荐阅读