如何从 pandas 数据框中的字符串术语中删除数字

问题描述 投票:0回答:5

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

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

想要删除“名称”列中的所有数字。

我最接近的是使用以下代码在cell级别上进行操作:

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

知道如何在 series/dataframe 级别以更好的方式做到这一点。

python string pandas
5个回答
124
投票

您可以结合正则表达式将 str.replace 应用于

Name
列:

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+
匹配的内容,即 1 个或多个数字,将被替换为空字符串。


17
投票

.str
没有必要。您可以将 pandas dataframe.replaceseries.replace
regex=True
参数一起使用。

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

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

inplace=True

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

10
投票

虽然问题听起来更笼统,但示例输入仅包含尾随数字。在这种情况下,您不必使用正则表达式,因为

.rstrip
(也可通过 .str
 对象的 
Series
 访问器
使用)可以做到这一点:

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

同样,您可以使用

.lstrip

 从开头删除任何数字,或使用 .strip
 从每个字符串的开头和结尾删除任何数字。


0
投票
出于某种原因,我不明白

.replace

对我不起作用。所以我用了:

df["Name"] = df["Name"].apply(lambda x: ''.join(y for y in x if not y.isdigit()))
提取除数字之外的所有内容。

© www.soinside.com 2019 - 2024. All rights reserved.