2016-09-21 77 views
3

我对根据其他列的总和创建熊猫数据框有疑问。根据另一列计算值的出现次数

例如,我有这样的数据帧

Country | Accident 
England   Car 
England   Car 
England   Car 
    USA    Car 
    USA    Bike 
    USA    Plane 
Germany   Car 
Thailand   Plane 

我想使基于基于该国的所有事故和值的另一个数据帧。我们将忽略事故类型,并根据国家进行总结。

我的愿望数据帧是这样

Country | Sum of Accidents 
    England    3 
    USA    3 
    Germany    1 
    Thailand    1 

回答

4

选项1
使用value_counts

df.Country.value_counts().reset_index(name='Sum of Accidents') 

enter image description here

选项2
使用groupby然后size

df.groupby('Country').size().sort_values(ascending=False) \ 
    .reset_index(name='Sum of Accidents') 

enter image description here

+0

感谢您的回答,这一个伟大的工程! –

3

可以使用groupby方法。

实施例 -

In [36]: df.groupby(["country"]).count().sort_values(["accident"], ascending=False).rename(columns={"accident" : "Sum of accidents"}).reset_index() 
Out[36]: 
    country Sum of accidents 
0 England     3 
1  USA     3 
2 Germany     1 
3 Thailand     1 

解释 -

df.groupby(["country"]).        # Group by country 
    count().           # Aggregation function which counts the number of occurences of country 
    sort_values(          # Sorting it 
     ["accident"],         
     ascending=False).   
    rename(columns={"accident" : "Sum of accidents"}). # Renaming the columns 
    reset_index()          # Resetting the index, it takes the country as the index if you don't do this.