📜  如何从Python的字符串中删除数字 – Pandas?

📅  最后修改于: 2022-05-13 01:54:41.271000             🧑  作者: Mango

如何从Python的字符串中删除数字 – Pandas?

在本文中,让我们看看如何在 Pandas 中从字符串中删除数字。目前,我们将仅使用 .csv 文件进行演示,但其他类型的文件的过程是相同的。函数read_csv()用于读取 CSV 文件。

这里 str。 replace() 将返回一个字符串,其中参数 'old' 将被参数 'new' 替换。现在让我们通过编码看看如何从 Pandas 数据框中的字符串中删除数字。



示例 1:

Python3
# 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)


Python3
# 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)


输出:

示例 2:

蟒蛇3

# 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)

输出: