pandas - Count number of counties per state using python {census} -


i troubling counting 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 series (from array) 

after this, i've tried using 2 approaches:

1:

    df[df['stname'] == serr] **//error: series length must match** 

2:

i = 0 name in serr:                        //this generate error 'alabama'     df['stname'] == name     in serr:         serr[i] == serr[name]         print(serr[name].count)         i+=1 

please guide me; has been 3 days stuff.

use groupby , aggregate county using nunique:

in [1]: import pandas pd  in [2]: df = pd.read_csv('census.csv')  in [3]: unique_counties = df.groupby('stname')['county'].nunique() 

now 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 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -