Press "Enter" to skip to content

Pandas字符串的处理

pandas的字符串处理:

  1. 使用方法:先获取Series的str属性,然后在属性上调用函数;
  2. 只能在字符串上使用,不能数字列上使用;
  3. Dataframe上没有str属性和处理方法;
  4. Series.str并不是Python原生字符串,而是自己的一套方法,不过大部分和str原生很相似;

今天演示的内容:

  1. 获取Series的str属性,然后使用各种字符串处理函数;

首先打开一份数据:

import pandas as pd

pd.set_option('display.unicode.ambiguous_as_wide', True)  #处理数据的列标题与数据无法对齐的情况
pd.set_option('display.unicode.east_asian_width', True)   #无法对齐主要是因为列标题是中文

df=pd.read_excel(r'data\2013tianqi_clear.xls',encoding='gbk')
print(df.head(15))
print(df.dtypes)

1、获取Series的str属性,然后使用各种字符串处理函数

import pandas as pd

pd.set_option('display.unicode.ambiguous_as_wide', True)  #处理数据的列标题与数据无法对齐的情况
pd.set_option('display.unicode.east_asian_width', True)   #无法对齐主要是因为列标题是中文

df=pd.read_excel(r'data\2013tianqi_clear.xls',encoding='gbk')

#字符串替换函数
df.loc[:,'最高温']=df['最高温'].str.replace('℃','')
df.loc[:,'最低温']=df['最低温'].str.replace('℃','')
print(df.head(20))

使用这个函数可以把列数的℃替换成空

替换完成之后,我们还可以去判断一下它是不是数字

import pandas as pd

pd.set_option('display.unicode.ambiguous_as_wide', True)  #处理数据的列标题与数据无法对齐的情况
pd.set_option('display.unicode.east_asian_width', True)   #无法对齐主要是因为列标题是中文

df=pd.read_excel(r'data\2013tianqi_clear.xls',encoding='gbk')

#字符串替换函数
df.loc[:,'最高温']=df['最高温'].str.replace('℃','')
df.loc[:,'最低温']=df['最低温'].str.replace('℃','')

#判断是不是数字
result=df['最高温'].str.isnumeric()

print(result)

2 Comments

  1. June 2021年11月12日

    哥,您那个html table 表格样式清理的页面404了哇,有新的地址没

    • Mr_huang 2021年11月12日

      可以访问这个:http://www.huanglucheng.com/table-clear/table.html

发表评论

您的电子邮箱地址不会被公开。