繁体   English   中英

如何从 pandas 列中的字符串中删除空格

[英]how to remove whitespace from string in pandas column

我需要删除 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()

这也没有删除空格。

使用带有拆分值条的列表理解,也可以在拆分之前剥离值以删除尾随; 、空格和"值:

f = lambda x: [y.strip('" ') for y in x.strip(';" ').split(';')]
df['magazine_list'] = df['magazine'].apply(f)
print (df)
  industry                                 magazine  \
0     Home  Goodhousekeeping.com; "Prevention.com";   
1  Fashion           Cosmopolitan; " Elle"; "Vogue"   
2  Fashion                             Vogue; "Elle   

                            magazine_list  
0  [Goodhousekeeping.com, Prevention.com]  
1             [Cosmopolitan, Elle, Vogue]  
2                           [Vogue, Elle]  

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

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

Output

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM