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