0

I am new to Python and programming in general. I have some experience with R and finding pandas a little difficult.

I am trying to conduct a frequency count and then return this as a DataFrame object.

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

x = df['Gender'].value_counts()

This returns the following series object:

       Gender
Male    200
Female  100

I want to convert this into a DataFrame object so I can plot and specify the axes information. This is where I am having a problem because .to_frame() cuts off the category label from the series.

x.to_frame()

returns

Gender
200
100

Is there a way to convert the series into a DataFrame and keep the category column? In R I think I could achieve this by using as.data.frame(x)

3
  • Hm, I cannot reproduce this. What version of pandas are you on? Commented Mar 8, 2017 at 23:25
  • Pandas version: 0.19.2, I'm using the Rodeo IDE which is a bit like RStudio but for Python if that makes a difference? Commented Mar 8, 2017 at 23:33
  • What exactly would you like the final plot to look like? It seems like the final plot should be a frequency histogram with two bins, male and female? The reason I ask is because I'm wondering why you need to convert the series to a data frame in the first place. Commented Mar 9, 2017 at 1:56

1 Answer 1

1

I would suggest the following:

import pandas as pd
df = pd.DataFrame({"gender": ["male", "female", "male", "male", "female"]})
df = df["gender"].value_counts().reset_index()
df

This returns:

    index   gender
0   male    3
1   female  2

Afterwards you can clean up by redefining the column names:

df.columns = ["gender", "counts"]
df

With the result:

    gender  counts
0   male    3
1   female  2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.