前面我們已經使用了字符串處理函數:
df['bWendu'].try.replace('℃', '').astype('int32')
Pandas的字符串處理:
1、使用方法:先獲取Series的str屬性,然后在屬性上調用函數;
2、只能在字符串列上使用,不能在數字列上使用;
3、DataFrame上沒有str屬性和處理方法;
4、Series.str並不是Python原生字符串,而是自己的一套方法,不過大部分和原生str很相似
Series.str字符串方法列表參考文檔
https://pandas.pydata.org/pandas-docs/stable/reference/series.html#string-handing
本節演示內容:
1、獲取Series的str屬性,然后使用各種字符串處理函數
2、使用str的startswith,contains等bool類Series可以做條件查詢
3、需要多次str處理的鏈式操作
4、使用正則表達式處理
import pandas as pd file_path = "../../datas/files/beijing_tianqi_2018.csv" df = pd.read_csv(file_path) print(df.head()) print(df.dtypes)
import pandas as pd file_path = "../../datas/files/beijing_tianqi_2018.csv" df = pd.read_csv(file_path) print('*' * 25, '打印前幾行數據', '*' * 25) print(df.head()) print('*' * 25, '打印每列數據類型', '*' * 25) print(df.dtypes) print('*' * 25, '獲取Series的str屬性', '*' * 25) print(df['bWendu'].str) print('*' * 25, '字符串替換函數', '*' * 25) df['bWendu'].str.replace('℃', '') print('*' * 25, '判斷是不是數字', '*' * 25) print(df['bWendu'].str.isnumeric()) print('*' * 25, '判斷是不是數字', '*' * 25) print(df['aqi'].str.len())
import pandas as pd file_path = "../../datas/files/beijing_tianqi_2018.csv" df = pd.read_csv(file_path) print('*' * 25, '打印前幾行數據', '*' * 25) print(df.head()) print('*' * 25, '打印每列數據類型', '*' * 25) print(df.dtypes) condition = df['ymd'].str.startswith('2018-03') print(condition) print(df[condition].head())
怎樣提取201803這樣的數字月份?
1、先將日期2018-03-31替換成20180331的形式
2、提取月份字符串201803
import pandas as pd file_path = "../../datas/files/beijing_tianqi_2018.csv" df = pd.read_csv(file_path) print('*' * 25, '打印前幾行數據', '*' * 25) print(df.head()) print('*' * 25, '打印每列數據類型', '*' * 25) print(df.dtypes) # 先將日期2018-03-31替換成20180331的形式 print('*' * 50) print(df['ymd'].str.replace('-', '')) # 每次調用函數,都返回一個新的Series # df['ymd'].str.replace('-', '').slice(0, 6) # 錯誤寫法 print('*' * 50) print(df['ymd'].str.replace('-', '').str.slice(0, 6)) # slice就是切片語法,可以直接使用 print('*' * 50) print(df['ymd'].str.replace('-', '').str[0:6])
import pandas as pd file_path = "../../datas/files/beijing_tianqi_2018.csv" df = pd.read_csv(file_path) print('*' * 25, '打印前幾行數據', '*' * 25) print(df.head()) print('*' * 25, '打印每列數據類型', '*' * 25) print(df.dtypes) # 添加新列 print('*' * 25, '添加新列', '*' * 25) def get_nianyyueri(x): year, month, day = x['ymd'].split('-') return f'{year}年{month}月{day}日' df['中文日期'] = df.apply(get_nianyyueri, axis=1) print(df['中文日期']) # 問題:怎樣將"2018年12月31日"中的年、月、日三個中文字符去掉 # 方法1:鏈式replace # print(df['中文日期'].str.replace('年', '').str.replace('月', '').str.replace('日', '')) # 方法2:正則表達式替換(推薦使用) # Series.str默認就開啟了正則表達式模式 print('*' * 25, '正則表達式替換', '*' * 25) print(df['中文日期'].str.replace('[年月日]', ''))