pandas处理字符串
阅读原文时间:2021年04月20日阅读:1

# pandas 字符串的处理

前面已经学习了字符串的处理函数

df["bWendu"].str.replace("℃","").astype(int32)

pandas的字符串处理

1 : 使用方法:先获取seriea的str属性,然后在属性上调用函数

2 : 只能在字符串列上使用,不能在数字列上使用

3 : DataFrame上没有str属性和处理方法

4 : Series.str并不是python原生字符串,而是自己的一套方法,不过大部分和原生str很相似

本节演示内容:

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

2 使用str的startswith、contain等bool类series可以做条件查询

3 需要多次str处理的链式操作

4 使用正则表达式的处理

0 读取北京的2018天气数据

import pandas as pd
df = pd.read_csv("beijing_tianqi_2018.csv")
df.dtypes

换掉温度后面的后缀

df.loc[:,"bWendu"] = df["bWendu"].str.replace("℃","").astype("int32")

df.loc[:,"yWendu"] = df["yWendu"].str.replace("℃","").astype("int32")

1 获取series的str属性,使用各种字符串处理函数

df["bWendu"].str

字符串替换函数

df["bWendu"].str.replace("℃","")

判断是不是数字

df["bWendu"].str.isnumeric()

df["aqi"].str.len()#AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

2 使用str的startseith、contains等得到bool的series可以做条件查询

condition = df["ymd"].str.startswith("2018-03")
df[condition].head()

3 需要多次str处理链式操作

实例:

1 先将日期2018-03-31替换成20180331的形式

2 提取月份字符串201803

df["ymd"].str.replace("-","")

每次调用函数,都返回一个新的series

df["ymd"].str.replace("-","").str.slice(0,6)

slice就是切片语法,可以直接用

df["ymd"].str.replace("-","").str[0:6]

4 使用正则表达式处理

添加新列

def get_nianyueri(x):
year,month,day = x["ymd"].split("-")
return f"{year}年{month}月{day}日"
df["中文日期"] =df.apply(get_nianyueri,axis= 1)

怎样将“2018年12月31日”中的年月日三个中文字符去除?

Series.str默认就开启了正则表达式模式

方法1

df["中文日期"].str.replace("年","").str.replace("月","").str.replace("日","")

方法2 :正则表达式替换

df["中文日期"].str.replace("[年月日]","")