與Python中的列表類似,可以使用for循環遍歷DataFrame或Series,但是這樣做(尤其是在大型數據集上)非常慢。
Pandas中提供了一個高效的替代方案:apply()方法。
語法
DataFrame.apply(func)
Series.apply(func)
- func – 要對數據集中所有元素執行的函數
下面的例子,對於DataFrame中的所有影片,評分大於8.0的標明”good”,否則標明”bad”。
首先,創建一個函數,如果評分>8.0,返回”good”,否則返回”bad”:
def rating_function(x): if x >= 8.0: return "good" else: return "bad"
現在,通過apply()把上面的函數應用到”rating”列中的所有元素:
# 加載數據 movies_df = pd.read_csv("IMDB-Movie-Data.csv", index_col="Title") movies_df.columns = ['rank', 'genre', 'description', 'director', 'actors', 'year', 'runtime', 'rating', 'votes', 'revenue_millions', 'metascore'] # 對"rating"列,應用rating_function movies_df["rating_category"] = movies_df["rating"].apply(rating_function) movies_df.head(2)
輸出
rank genre ... metascore rating_category Title ... Guardians of the Galaxy 1 Action,Adventure,Sci-Fi ... 76.0 good Prometheus 2 Adventure,Mystery,Sci-Fi ... 65.0 bad [2 rows x 12 columns]
apply()方法對rating列中所有元素執行rating_function函數,然后返回一個新的Series。這個系列分配給一個名為rating_category的新列。
apply()方法中,還可以使用匿名函數。這個lambda函數實現了與rating_function相同的功能:
movies_df["rating_category"] = movies_df["rating"].apply(lambda x: 'good' if x >= 8.0 else 'bad') movies_df.head(2)
輸出
rank genre ... metascore rating_category Title ... Guardians of the Galaxy 1 Action,Adventure,Sci-Fi ... 76.0 good Prometheus 2 Adventure,Mystery,Sci-Fi ... 65.0 bad [2 rows x 12 columns]
總的來說,使用apply()要比手工遍歷行快得多,因為Pandas內部使用了向量化。
向量化: 一種計算機編程風格,操作應用於整個數組而不是單個元素 – wikipedia
apply()在自然語言處理(NLP)中的高使用率就是一個很好的例子。自然語言處理(NLP)時,需要將各種文本清理功能應用於字符串,以便為機器學習做准備。
