如何计算具有相同索引的元素?

时间:2019-07-17 21:12:08

标签: python pandas

我必须从CSV文件中获取每个州的县数,然后返回哪个州的县数最多。但是我不知道如何计算相同索引下的元素

csv文件: enter image description here

我尝试使用.count()和numerate(),但返回一个错误键错误:“ Alabama”

这是我用来从CSV文件创建实际数据帧的代码

import pandas as PD

census = pd.read_csv('census.csv')
counties = pd.DataFrame({'State':census['STNAME'],'County':census['CTYNAME'],
         'populations':census['CENSUS2010POP'],'population 2010': census['POPESTIMATE2010'], 
         'population 2015': census['POPESTIMATE2015']})
counties = counties.set_index(['State', 'County'])

1 个答案:

答案 0 :(得分:0)

尝试:

counties.groupby(['State','County']).agg('count')

代替:

counties = counties.set_index(['State', 'County']).count()