Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.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 获取每个元素出现次数的最快方法_Python_Pandas - Fatal编程技术网

Python 获取每个元素出现次数的最快方法

Python 获取每个元素出现次数的最快方法,python,pandas,Python,Pandas,我有一个像这样的大数据框 name Country ... 1 Paul Germany 2 Paul Germany 3 G

我有一个像这样的大数据框

                                             name     Country   ... 
1                                            Paul     Germany
2                                            Paul     Germany
3                                          George     Italy
3                                          George     Italy   
3                                          George     Italy
                       ...
N                                            John     USA
我要查找name列中每个元素的出现情况,例如has

                                             name     Country   Count 
1                                            Paul     Germany    2000
2                                          George     Italy       500
                          ...
N                                            John     USA       40000
你知道最理想的方法是什么吗

因为这相当长

df['count'] = df.groupby(['name'])['name'].transform(pd.Series.value_counts)

您可以这样做:

df.groupby(['name', 'Country']).size()
例如:

import pandas as pd

df = pd.DataFrame.from_dict({'name' : ['paul', 'paul', 'George', 'George', 'George'],
    'Country': ['Germany', 'Italy','Germany','Italy','Italy']})

df
输出:

    Country name
0   Germany paul
1   Italy   paul
2   Germany George
3   Italy   George
4   Italy   George
name    Country
George  Germany    1
        Italy      2
paul    Germany    1
        Italy      1
分组方式和获取计数:

df.groupby(['name', 'Country']).size()
输出:

    Country name
0   Germany paul
1   Italy   paul
2   Germany George
3   Italy   George
4   Italy   George
name    Country
George  Germany    1
        Italy      2
paul    Germany    1
        Italy      1

如果您只想计算与
名称
列相关的计数,则不需要使用
groupby
,只需使用从数据帧中选择
名称
列(它返回一个
系列
对象)并直接对其调用
值_counts()

df['name'].value_counts()

为什么第二个数据帧中的第二行是意大利的乔治,而不是第一行中的德国的保罗?我也想删除重复项,但这不是必须的