熊猫的pivot_table分组列按值

Bru*_*ira 5 python pivot-table pandas

我正在尝试将数值用作Pandas数据透视表上的列。问题在于,由于每个数字大部分都是唯一的,因此生成的数据透视表作为汇总数据的方式不是很有用。

这是我到目前为止(假数据示例):

import pandas as pd   

df = pd.DataFrame({'Country': ['US', 'Brazil', 'France', 'Germany'], 
                       'Continent': ['Americas', 'Americas', 'Europe', 'Europe'], 
                       'Population': [321, 207, 80, 66]})


pd.pivot_table(df, index='Continent', columns='Population', aggfunc='count')
Run Code Online (Sandbox Code Playgroud)

这是生成的ivot_table的图像 。

如何根据列将值分组到范围内?

换句话说,我该如何计算人口... <100、100-200,> 300的所有国家?

Sco*_*ton 6

使用pd.cut:

df = df.assign(PopGroup=pd.cut(df.Population,bins=[0,100,200,300,np.inf],labels=['<100','100-200','200-300','>300']))
Run Code Online (Sandbox Code Playgroud)

输出:

  Continent  Country  Population PopGroup
0  Americas       US         321     >300
1  Americas   Brazil         207  200-300
2    Europe   France          80     <100
3    Europe  Germany          66     <100

pd.pivot_table(df, index='Continent', columns='PopGroup',values=['Country'], aggfunc='count')
Run Code Online (Sandbox Code Playgroud)

输出:

        Country          
PopGroup  200-300 <100 >300
Continent                  
Americas      1.0  NaN  1.0
Europe        NaN  2.0  NaN
Run Code Online (Sandbox Code Playgroud)