Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Pandas-计算每列的不同值_Python_Pandas_Dictionary_Group By - Fatal编程技术网

Python Pandas-计算每列的不同值

Python Pandas-计算每列的不同值,python,pandas,dictionary,group-by,Python,Pandas,Dictionary,Group By,我有一个如下所示的数据帧: Id ActivityId ActivityCode 1 2 3 1 2 4 1 3 2 我需要获得与该Id相关的不同活动Id的计数 在上面的示例中,id 1将返回2,因为该id有两个不同的活动id SQL应该是这样的: SELECT COUNT(DISTINCT ActivityId) FROM table GROUP BY Id 我如何在熊猫身上做到这一点 (如果可能,我想知道是否有一种

我有一个如下所示的数据帧:

Id ActivityId ActivityCode

1   2           3
1   2           4
1   3           2
我需要获得与该Id相关的不同活动Id的计数

在上面的示例中,id 1将返回2,因为该id有两个不同的活动id

SQL应该是这样的:

SELECT COUNT(DISTINCT ActivityId) FROM table GROUP BY Id
我如何在熊猫身上做到这一点

(如果可能,我想知道是否有一种方法可以在字典中获得结果,而无需手动迭代)

我认为您需要:

对于
dict
添加:


很高兴能帮忙,祝你好运!
print (df)
   Id  ActivityId  ActivityCode
0   1           2             3
1   1           2             4
2   1           3             2
3   2           8             7

df = df.groupby('Id')['ActivityId'].nunique()
print (df)
Id
1    2
2    1
Name: ActivityId, dtype: int64
d = df.groupby('Id')['ActivityId'].nunique().to_dict()
print (d)
{1: 2, 2: 1}