Prova12
Prova12

Reputation: 653

Name with title a pandas dataframe

I am trying to add a name to my pandas df but I am failing. I want the two columns to be named "Job department" and "Amount"

df["sales"].value_counts()
>>>>>>output
sales          4140
technical      2720
support        2229
IT             1227
product_mng     902
marketing       858
RandD           787
accounting      767
hr              739
management      630
Name: sales, dtype: int64

Then I do:

job_frequency = pd.DataFrame(df["sales"].value_counts(), columns=['Job department','Amount'])
print(job_frequency)

but I get:

Empty DataFrame
Columns: [Job department, Amount]
Index: []

Upvotes: 1

Views: 392

Answers (2)

Andrew Li
Andrew Li

Reputation: 549

job_frequency = pd.DataFrame(
    data={
        'Job department': df["sales"].value_counts().index,
        'Amount': df["sales"].value_counts().values
    }
)

Upvotes: 0

jezrael
jezrael

Reputation: 862671

Use DataFrame.rename_axis for index name with Series.reset_index for convert Series to DataFrame:

job_frequency = (df["sales"].value_counts()
                            .rename_axis('Job department')
                            .reset_index(name='Amount'))

print(job_frequency)
  Job department  Amount
0          sales    4140
1      technical    2720
2        support    2229
3             IT    1227
4    product_mng     902
5      marketing     858
6          RandD     787
7     accounting     767
8             hr     739
9     management     630

Upvotes: 3

Related Questions