Antony Joy
Antony Joy

Reputation: 301

How to get a default index or index with number in python dataframe?

I have a dataframe which has the 10 unique countries within 100 rows. Now by applying value_counts(), I am trying to get the frequency of occurance of each country. I need this to be in a dataframe.

This is the output of value_counts:
South Africa    166
USA             164
Spain           134
Sweeden         119
France          115
Russia           97
India            95
UK               95
Ukraine           9
Ireland           5
Name: Country, dtype: int64

I need this to be made into a new dataframe, but it should have index values as 0,1,2.... I tried below country=pd.DataFrame(so_survey_df['Country'].value_counts())

but it gave a dataframe with Country name as index.

Upvotes: 1

Views: 1063

Answers (2)

Armin
Armin

Reputation: 61

So basically you need to count the values, reset the index and change the columns name, thus a one line code can be:

country = so_survey_df['Country'].value_counts().reset_index(name='Count').rename(columns={'index':'Country'})

Upvotes: 2

ashkangh
ashkangh

Reputation: 1624

Try this:

pd.Series({val:k for k,val in df['country'].value_counts().iteritems()})

Output:

166    South Africa
164             USA
134           Spain
119         Sweeden
115          France
97           Russia
95               UK
9           Ukraine
5           Ireland
dtype: object

Upvotes: 0

Related Questions