Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

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.

1 Answer

0 votes
by (41.4k points)
edited by

You can use groupby() and aggregate COUNTY using nunique().

This is how the code looks:

 import pandas as pd

df = pd.read_csv('census.csv')

unique_counties = df.groupby('STNAME')['COUNTY'].nunique()

So, the result will be:

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

Get your master's degree in Data Science right now. Enroll in MSc Data Science in Philippines!

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...