如何在Python Pandas中移除字符串中的数字

如何在Python Pandas中移除字符串中的数字

在这篇文章中,让我们看看如何在Pandas中移除字符串中的数字。目前,我们将只使用.csv文件进行演示,但这个过程对其他类型的文件也是一样的。函数read_csv()是用来读取CSV文件的。

语法:

replace()
str.replace(old, new)
Python

这里str.replace()将返回一个字符串,其中的参数’old’将被参数’new’所取代。现在让我们通过编码看看如何从pandas数据框架中的字符串中删除数字。

示例 1:

# code
import pandas as pd
  
  
# creating dataframe
df = pd.DataFrame.from_dict({'Name': ['May21', 'James',
                                      'Adi22', 'Hello',
                                      'Girl90'],
                               
                             'Age': [25, 15, 20, 33, 42],
                               
                               
                             'Income': [21321, 12311, 25000,
                                        32454, 65465]})
  
# removing numbers from strings of speciafied 
# column, here 'Name'
df['Name'] = df['Name'].str.replace('\d+', '')
  
# display output with numbers removed from 
# required strings
print(df)
Python

输出:

如何在Python中移除字符串中的数字 - Pandas?

示例 2:

# code
import pandas as pd
  
  
# creating dataframe
df = pd.DataFrame.from_dict({'Name': ['rohan21', 'Jelly',
                                      'Alok22', 'Hey65',
                                      'boy92'],
                               
                             'Age': [24, 25, 10, 73, 92],
                               
                             'Income': [28421, 14611, 28200,
                                        45454, 66565]})
  
# removing numbers from strings of speciafied 
# column, here 'Name'
df['Name'] = df['Name'].str.replace('\d+', '')
  
# display output with numbers removed from 
# required strings
print(df)
Python

输出:

如何在Python中移除字符串中的数字 - Pandas?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册