计数 Pandas 中每组的唯一值
Ahmed Waheed
2023年1月30日
当我们处理大型数据集时,有时我们必须将某些功能应用于特定的数据组。例如,我们有一个国家数据集和用于私人事务的私人代码数据集。我们要计算一个国家使用的代码数量。下面列出了计数唯一值的不同方法。
在以下各节中,我们将使用相同的 DataFrame
,如下所示:
import pandas as pd
data = [
[999, "Switzerland"],
[113, "Switzerland"],
[112, "Japan"],
[112, "Switzerland"],
[113, "Canada"],
[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
4 113 Canada
5 114 Japan
6 100 Germany
7 114 Japan
8 115 Germany
df.groupby().nunique()
方法
让我们看看 df.groupby().nunique()
函数如何对我们的国家进行分组。
import pandas as pd
data = [
[999, "Switzerland"],
[113, "Switzerland"],
[112, "Japan"],
[112, "Switzerland"],
[113, "Canada"],
[114, "Japan"],
[100, "Germany"],
[114, "Japan"],
[115, "Germany"],
]
df = pd.DataFrame(data, columns=["code", "Countries"])
result = df.groupby("Countries")["code"].nunique()
print(result)
输出:
Countries
Canada 1
Germany 2
Japan 2
Switzerland 3
Name: code, dtype: int64
这表明加拿大使用的是一个代码,德国使用的是两个代码,依此类推。
df.groupby().agg()
方法
该方法与 df.groupby().nunique()
相同。我们需要将 nunique()
函数传递给 agg()
函数。
import pandas as pd
data = [
[999, "Switzerland"],
[113, "Switzerland"],
[112, "Japan"],
[112, "Switzerland"],
[113, "Canada"],
[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
0 Canada 1
1 Germany 2
2 Japan 2
3 Switzerland 3
.agg({'code': pd.Series.nunique})
它使用 pd.Series.nunique
函数对列 code
进行聚集。
df.groupby().unique()
方法
当你想查看哪个国家使用哪些代码时,此方法很有用。
import pandas as pd
data = [
[999, "Switzerland"],
[113, "Switzerland"],
[112, "Japan"],
[112, "Switzerland"],
[113, "Canada"],
[114, "Japan"],
[100, "Germany"],
[114, "Japan"],
[115, "Germany"],
]
result = df.groupby("Countries")["code"].unique()
print(result)
输出:
Countries
Canada [113]
Germany [100, 115]
Japan [112, 114]
Switzerland [999, 113, 112]
Name: code, dtype: object