gpt4 book ai didi

python - Pandas 计算数据框中不同的多列并按多列分组

转载 作者:行者123 更新时间:2023-12-02 00:12:07 25 4
gpt4 key购买 nike

<分区>

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com