開始使用免費開始

運用 pandas 的功能:groupby

本課程會著重在 GeoPandas 的空間功能,但別忘了你手上仍是一個 dataframe,你熟悉的所有 pandas 功能都仍然適用。

在這個練習中,我們要複習一個常見的功能:groupby 操作。當你有一個欄位用來表示群組,並且想為每個群組計算一個統計量時,就會用到它。在 groupby() 方法中,你要傳入包含群組的欄位。接著,在回傳的物件上呼叫你想對每個群組計算的函式。在這個練習中,我們想知道各種餐廳類型的每個群組大小。

若想進一步了解 groupby 操作並多做一些練習,請參考「Manipulating DataFrames with pandas」課程。

本練習屬於課程

在 Python 中處理地理空間資料

檢視課程

練習說明

  • 使用 groupby() 依餐廳的「type」分組,並計算各組大小。將結果命名為 type_counts
  • 列印結果的 Series。

動手互動練習

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

# Load the restaurants data
restaurants = geopandas.read_file("paris_restaurants.geosjon")

# Calculate the number of restaurants of each type
type_counts = restaurants.groupby(____).____()

# Print the result
print(____)
編輯並執行程式碼