如何在 Pandas 数据框中从字符串术语中删除数字

57

我有一个类似于以下数据框的数据:

Name    Volume  Value
May21   23      21321
James   12      12311
Adi22   11      4435
Hello   34      32454
Girl90  56      654654

我希望输出的格式为:

Name    Volume  Value
May     23      21321
James   12      12311
Adi     11      4435
Hello   34      32454
Girl    56      654654

想要从名称列中删除所有数字。

我最接近的方法是使用以下代码在单元格级别进行操作:

result = ''.join([i for i in df['Name'][1] if not i.isdigit()])

有什么更好的方法在系列/数据框级别上完成它吗。

4个回答

124
你可以使用正则表达式将 Name 列与 str.replace 结合起来进行应用:
import pandas as pd

# Example DataFrame
df = pd.DataFrame.from_dict({'Name'  : ['May21', 'James', 'Adi22', 'Hello', 'Girl90'],
                             'Volume': [23, 12, 11, 34, 56],
                             'Value' : [21321, 12311, 4435, 32454, 654654]})

df['Name'] = df['Name'].str.replace('\d+', '')

print(df)

输出:

    Name   Value  Volume
0    May   21321      23
1  James   12311      12
2    Adi    4435      11
3  Hello   32454      34
4   Girl  654654      56
在正则表达式中,\d 表示“任何数字”,+ 表示“一个或多个”。
因此,str.replace('\d+', '') 的意思是:“用空字符串替换字符串中出现的所有数字”。

22

你可以这样做:

df.Name = df.Name.str.replace('\d+', '')

要玩和探索,请查看在线正则表达式演示,链接在这里:https://regex101.com/r/Y6gJny/2

任何与模式 \d+ 匹配的内容,即一个或多个数字,都将被替换为空字符串。


16

.str不是必须的。您可以使用Pandas dataframe.replaceseries.replaceregex=True参数。

df.replace('\d+', '', regex=True)

如果您想更改源数据框,请使用 inplace=True

df.replace('\d+', '', regex=True, inplace=True)

我们可以使用这个工具来移除坏数据,例如数字值之间有空格吗?比如 "12 445"。 - curiouscheese

9

虽然问题听起来更为普遍,但示例输入只包含尾部数字。在这种情况下,您不必使用正则表达式,因为.rstrip(也可通过Series对象的.str访问器进行访问)可以完美地解决这个问题。

import string
df['Name'] = df['Name'].str.rstrip(string.digits)

同样地,您可以使用 .lstrip 方法从开头删除任何数字,或者使用 .strip 方法来移除每个字符串开头和结尾的任何数字。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接