使用python {census}计算每个州的县数 [英] Count number of counties per state using python {census}
本文介绍了使用python {census}计算每个州的县数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我感到困扰的是使用着名的 cenus.csv 数据。
任务:计算每个州的县数。
我已经尝试过:
df = pd.read_csv('census.csv')
dfd = df [:] ['STNAME']。unique()//给出状态
serr = pd.Series(dfd)//转换为系列(从数组)
之后,我尝试使用两种方法:
1:
df [df ['STNAME'] == serr] ** //错误:系列长度必须匹配**
2:
i = 0
在serr中的名称://这会生成错误'阿拉巴马州'
df ['STNAME'] ==名字
为我在serr:
se rr [i] == serr [name]
print(serr [name] .count)
i + = 1
请指导我;这个东西已经三天了。
解决方案
使用 groupby
使用 nunique
的 COUNTY
:
code>在[1]中:将大熊猫导入为pd
在[2]中:df = pd.read_csv('census.csv')
在[3 ]:unique_counties = df.groupby('STNAME')['COUNTY']。nunique()
现在结果
在[4]中:unique_counties
Out [4]:
STNAME
阿拉巴马州68
阿拉斯加州30
亚利桑那州16
阿肯色州76
加州59
科罗拉多州65
康涅狄格州9
特拉华州4
区哥伦比亚2
佛罗里达68
格鲁吉亚160
夏威夷6
爱达荷45
伊利诺伊州103
印第安纳州93
爱荷华州100
堪萨斯州106
肯塔基州121
路易斯安那州65
缅因州17
马里兰州25
马萨诸塞州15
密歇根州84
明尼苏达州88
密西西比州83
密苏里州116
蒙大拿州57
内布拉斯加州94
内华达州18
新罕布什尔州11
新泽西州22
新墨西哥州34
纽约63
北卡罗来纳州101
北达科他州54
俄亥俄州89
俄克拉荷马州78
俄勒冈州37
宾夕法尼亚州68
罗德岛6
南卡罗来纳州47
南达科他州67
田纳西州96
德克萨斯州255
犹他州30
佛蒙特州15
弗吉尼亚州134
华盛顿州40
西维吉尼亚州56
威斯康星州73
怀俄明州24
名称:COUNTY,dtype:int64
I am troubling with counting the number of counties using famous cenus.csv data.
Task: Count number of counties in each state.
Facing comparing (I think) / Please read below?
I've tried this:
df = pd.read_csv('census.csv')
dfd = df[:]['STNAME'].unique() //Gives out names of state
serr = pd.Series(dfd) // converting to series (from array)
After this, i've tried using two approaches:
1:
df[df['STNAME'] == serr] **//ERROR: series length must match**
2:
i = 0
for name in serr: //This generate error 'Alabama'
df['STNAME'] == name
for i in serr:
serr[i] == serr[name]
print(serr[name].count)
i+=1
Please guide me; it has been three days with this stuff.
解决方案
Use groupby
and aggregate COUNTY
using nunique
:
In [1]: import pandas as pd
In [2]: df = pd.read_csv('census.csv')
In [3]: unique_counties = df.groupby('STNAME')['COUNTY'].nunique()
Now the results
In [4]: unique_counties
Out[4]:
STNAME
Alabama 68
Alaska 30
Arizona 16
Arkansas 76
California 59
Colorado 65
Connecticut 9
Delaware 4
District of Columbia 2
Florida 68
Georgia 160
Hawaii 6
Idaho 45
Illinois 103
Indiana 93
Iowa 100
Kansas 106
Kentucky 121
Louisiana 65
Maine 17
Maryland 25
Massachusetts 15
Michigan 84
Minnesota 88
Mississippi 83
Missouri 116
Montana 57
Nebraska 94
Nevada 18
New Hampshire 11
New Jersey 22
New Mexico 34
New York 63
North Carolina 101
North Dakota 54
Ohio 89
Oklahoma 78
Oregon 37
Pennsylvania 68
Rhode Island 6
South Carolina 47
South Dakota 67
Tennessee 96
Texas 255
Utah 30
Vermont 15
Virginia 134
Washington 40
West Virginia 56
Wisconsin 73
Wyoming 24
Name: COUNTY, dtype: int64
这篇关于使用python {census}计算每个州的县数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文