【python學習筆記】44:Series.apply()列資料批量處理,Series.str.extract()正則匹配
阿新 • • 發佈:2018-11-19
學習《Python3爬蟲、資料清洗與視覺化實戰》時自己的一些實踐。
Series.apply()列資料批量處理
先將該列取出,形成Series物件,再呼叫apply()
方法傳入用於處理的函式,這個過程就像map()
一樣。
import pandas as pd
# 各國人口資料檔案
df_pop = pd.read_csv("E:/Data/practice/european_cities.csv")
# print(df_pop.head())
# 檢視欄位的資料型別.用這種方式檢視到的object(文字)就是str型別
print(df_pop.dtypes)
# 這裡表明兩種寫法是一樣的,都返回這一列的Series物件
print(df_pop['Population'] is df_pop.Population) # True
# 對人口欄位,刪除逗號並轉為int:這裡apply()函式傳入一個函式,將對Series中的每個項呼叫該函式
df_pop['Population'] = df_pop.Population.apply(lambda x: int(x.replace(",", "")))
# print(df_pop.head())
# 讀取State列的前三個資料看一下
ary = df_pop['State' ].values[:3]
print(ary) # [' United Kingdom' ' Germany' ' Spain']
# 去掉State欄位中資料兩端的空格
df_pop['State'] = df_pop.State.apply(lambda x: x.strip())
# print(df_pop.head())
Series.str.extract()正則匹配
import pandas as pd
# 中國旅遊網的文章標題和連結資料
df = pd.read_csv("E:/Data/practice/getlinks.csv")
# print(df.head())
# 這裡df.link即獲取link這一列形成Series物件
# Series物件的str屬性的extract()方法,將對Series物件中的每個項用指定的正則方式匹配並生成匹配後的DataFrame
# 沒有匹配到的部分在生成的DF物件中將被設定成NaN
df1 = df.link.str.extract(r'(\d+)') # 匹配數字
# print(df1.head())
# 匹配'.'任意字元'/'數字,因為是兩部分所以生成的DF物件有兩列
df2 = df.link.str.extract(r'(.*)/(\d)')
# print(df2.head())
# 在括號內最前面寫'?P<列名>'可以為生成的DF物件新增列名
df3 = df.link.str.extract(r'(?P<URL>.*)/(?P<ID>\d+)') # 匹配的內容和df2是一樣的
# print(df3.head())
另外書上沒有講expand
引數,該引數預設是True,當設定為False時,對於只匹配一個組的模式(如上例中的df1)將返回一個Series物件,而不再是DF物件。
# 這時返回一個Series,而不是單列的DF
s4 = df.link.str.extract(r'(\d+)', expand=False)
# print(s4.head())