Pandas字符串处理
前面我们已经使用了字符串的处理函数:
df["bWendu"].str.replace("℃", "").astype('int32')
Pandas的字符串处理:
- 使用方法:先获取Series的str属性,然后在属性上调用函数;
- 只能在字符串列上使用,不能数字列上使用;
- Dataframe上没有str属性和处理方法
- Series.str并不是Python原生字符串,而是自己的一套方法,不过大部分和原生str很相似;
Series.str字符串方法列表参考文档:
https://pandas.pydata.org/pandas-docs/stable/reference/series.html#string-handling
本章内容:
- 获取Series的str属性,然后使用各种字符串处理函数
- 使用str的startswith、contains等bool类Series可以做条件查询
- 需要多次str处理的链式操作
- 使用正则表达式的处理
1、判断是不是数字
import pandas as pd
df = pd.read_csv("../beijing_tianqi_2018.csv")
a=df["bWendu"].str.replace("℃","")
b=df["yWendu"].str.replace("℃","")
#判断是不是数字
c = df["bWendu"].str.isnumeric()
print(c)
2、使用str的startswith,contains等得到bool的Series可以做条件查询
condition = df["ymd"].str.startswith("2018-03")
# print(condition)
d = df[condition].head()
print(d)
3、需要多次str处理的链式操作
怎样提取201803这样的数字月份?
1、先将日期2018-03-31替换成20180331的形式
2、提取月份字符串201803
c = df["ymd"].str.replace("-","").str.slice(0,6)
print(c)
4. 使用正则表达式的处理
添加新列
def get_new_col(x):
year,month,day = x["ymd"].split("-")
return f"{year}年{month}月{day}日"
df["中文日期"] = df.apply(get_new_col,axis = 1)
print(df["中文日期"])
将“2018年12月31日”中的年、月、日三个中文字符去除?
#链式str
d = df["中文日期"].str.replace("年","").str.replace("月","").str.replace("日","")
print(d)
#正则
e = df["中文日期"].str.replace("[年月日]","")
print(e)