# 計數 Pandas 中每組的唯一值

Ahmed Waheed 2023年1月30日

``````import pandas as pd

data = [
[999, "Switzerland"],
[113, "Switzerland"],
[112, "Japan"],
[112, "Switzerland"],
[114, "Japan"],
[100, "Germany"],
[114, "Japan"],
[115, "Germany"],
]
df = pd.DataFrame(data, columns=["code", "Countries"])
print(df)
``````

``````   code    Countries
0   999  Switzerland
1   113  Switzerland
2   112        Japan
3   112  Switzerland
5   114        Japan
6   100      Germany
7   114        Japan
8   115      Germany
``````

## `df.groupby().nunique()` 方法

``````import pandas as pd

data = [
[999, "Switzerland"],
[113, "Switzerland"],
[112, "Japan"],
[112, "Switzerland"],
[114, "Japan"],
[100, "Germany"],
[114, "Japan"],
[115, "Germany"],
]

df = pd.DataFrame(data, columns=["code", "Countries"])
result = df.groupby("Countries")["code"].nunique()
print(result)
``````

``````Countries
Germany        2
Japan          2
Switzerland    3
Name: code, dtype: int64
``````

## `df.groupby().agg()` 方法

``````import pandas as pd

data = [
[999, "Switzerland"],
[113, "Switzerland"],
[112, "Japan"],
[112, "Switzerland"],
[114, "Japan"],
[100, "Germany"],
[114, "Japan"],
[115, "Germany"],
]
df = pd.DataFrame(data, columns=["code", "Countries"])
result = df.groupby(by="Countries", as_index=False).agg({"code": pd.Series.nunique})
print(result)
``````

``````     Countries  code
1      Germany     2
2        Japan     2
3  Switzerland     3
``````
``````.agg({'code': pd.Series.nunique})
``````

## `df.groupby().unique()` 方法

``````import pandas as pd

data = [
[999, "Switzerland"],
[113, "Switzerland"],
[112, "Japan"],
[112, "Switzerland"],
[114, "Japan"],
[100, "Germany"],
[114, "Japan"],
[115, "Germany"],
]
result = df.groupby("Countries")["code"].unique()
print(result)
``````

``````Countries