小编wal*_*ter的帖子

Pandas 对数据框中不同的多列进行计数并按多列进行分组

我找到了答案 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 中获得相同的结果?

python pandas pandas-groupby

2
推荐指数
1
解决办法
2万
查看次数

标签 统计

pandas ×1

pandas-groupby ×1

python ×1