<分区>
我找到了答案 test2 = test_pd.groupby(by = ['ID'])['国家','颜色'].nunique().reset_index()
idk 为什么当 rafael 提供的链接没有回答问题时这个问题被标记为重复
我有一个包含 3 列的数据框:
country color ID
0 Germany Red 12
1 France Red 13
2 US Blue 11
3 France Red 11
如果我想在 SQL 中找出每个 ID 的不同国家和颜色的数量,它将是
select ID
, count(distinct(country)) as num_countries
, count(distinct(color)) as num_color
from table_name
group by ID;
结果是这样的
ID num_countries num_color
0 12 1 1
0 11 2 2
0 13 1 1
如何在 Pandas 中获得相同的结果?