使用 filter() 進行資料篩選

使用 pandas 撰寫高效程式碼

Leonidas Souliotis

PhD Candidate

filter() 的用途

根據彙總特徵限制結果

  • 遺漏值數量
  • 特定特徵的平均值
  • 群組出現次數
使用 pandas 撰寫高效程式碼

使用 groupby().filter() 篩選

restaurant_grouped = restaurant.groupby('day')
filter_trans = lambda x : x['total_bill'].mean() > 20
restaurant_filtered = restaurant_grouped.filter(filter_trans)
使用 .filter() 的時間 0.00414085388184 秒
print(restaurant_filtered['tip'].mean())
3.11527607362
print(restaurant['tip'].mean())
2.9982786885245902
使用 pandas 撰寫高效程式碼

與原生方法比較

t=[restaurant.loc[df['day'] == i]['tip'] for i in restaurant['day'].unique() 
    if restaurant.loc[df['day'] == i]['total_bill'].mean()>20]
restaurant_filtered = t[0]
for j in t[1:]: 
    restaurant_filtered=restaurant_filtered.append(j,ignore_index=True)
使用原生 Python 的時間:0.00663900375366 秒
print(restaurant_filtered.mean())
3.11527607362
時間差異:60.329341317157024%
使用 pandas 撰寫高效程式碼

開始動手做!

使用 pandas 撰寫高效程式碼

Preparing Video For Download...