提问者:小点点

在python pandas中删除单词中的空格


嗨,我有一个df是这样的

Product
Prod1
Prod 1
Prod2
Prod 2
Prod 2
Prod 3
Prod3  and so on

我基本上想把所有这些Prod1,Prod2和Prod3等转换成分类变量。 为此,我需要删除Prod和数字之间的空格,例如删除Prod和1之间的空格,使Prod1,Prod1等变为Prod1,这样就没有相同产品的重复条目

上表的预期输出

Product
Prod1
Prod1
Prod2
Prod2
Prod2
Prod3
Prod3  and so on

所有的回答都是为了一句话而提到的。 我想要一个答案,它可以复制到整个表,并删除一列中所有单词之间的空白


共3个答案

匿名用户

使用str.split().agg(“”.join)

例如:

df['Product'] = df['Product'].str.split().agg("".join)
#or
#df['Product'] = df['Product'].str.replace(r"(\s+)", "")
print(df)

输出:

  Product
0   Prod1
1   Prod1
2   Prod2
3   Prod2
4   Prod2
5   Prod3
6   Prod3

匿名用户

让我们尝试使用以下模式str.replace来删除proddigits之间的空格。

df['Product'] = df.Product.str.replace('(Prod)(\s+)(\d)', r'\1\3')

输出:

            Product
0             Prod1
1             Prod1
2             Prod2
3             Prod2
4             Prod2
5             Prod3
6  Prod3  and so on

匿名用户

试试看:

df["Product"] = [i.replace(" ", "") for i in df.Product]