開始使用免費開始

使用 pandas 分組資料

資料管線的輸出通常是「建模後」的資料集。這類資料集能讓資料使用者更容易取得資訊,而不必再做太多處理。用 pandas 進行分組有助於建立這種建模後的資料集。

已將 pandas 載入為 pd,而 raw_testing_scores DataFrame 的資料形式如下:

              street_address       city  math_score  reading_score  writing_score
01M539   111 Columbia Street  Manhattan       657.0          601.0          601.0
02M294      350 Grand Street  Manhattan       395.0          411.0          387.0
02M308      350 Grand Street  Manhattan       418.0          428.0          415.0

本練習屬於課程

使用 Python 的 ETL 與 ELT

檢視課程

練習說明

  • 使用 .loc[] 只保留 "city""math_score""reading_score""writing_score" 這些欄位。
  • "city" 欄位對 DataFrame 分組,並計算各城市的數學、閱讀、寫作成績的平均值。
  • 使用 transform() 函式建立分組後的 DataFrame。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def transform(raw_data):
	# Use .loc[] to only return the needed columns
	raw_data = raw_data.____[:, ____]
	
    # Group the data by city, return the grouped DataFrame
	grouped_data = raw_data.____(by=["____"], axis=0).____()
	return grouped_data

# Transform the data, print the head of the DataFrame
grouped_testing_scores = ____(raw_testing_scores)
print(grouped_testing_scores.head())
編輯並執行程式碼