統計 Python Pandas 中每組的唯一值


要統計 Python Pandas 中每組的唯一值,我們可以使用df.groupby('column_name').count()

步驟

  • 建立一個二維、可變大小、可能異構的表格資料,df
  • 列印輸入的 DataFrame,df
  • 使用df.groupby('rank')['id'].count()查詢每組的唯一值計數並將其儲存在變數“count”中。
  • 列印步驟 3 中的計數。

示例

import pandas as pd

df = pd.DataFrame(
    {
       "id": [1, 2, 1, 3, 5, 1, 4, 3, 6, 7],
       'rank': [1, 4, 1, 2, 1, 4, 6, 1, 5, 3]
    }
)

print"Input DataFrame 1 is:\n", df
count = df.groupby('rank')['id'].count()
print"Frequency of ranks:\n", count

輸出

Input DataFrame 1 is:

   id  rank
0   1    1
1   2    4
2   1    1
3   3    2
4   5    1
5   1    4
6   4    6
7   3    1 
8   6    5
9   7    3
Frequency of ranks:
rank
1  4
2  1
3  1
4  2
5  1
6  1
Name: id, dtype: int64

更新於:14-Sep-2021

6K+ 檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.