Home > Back-end >  How do you reset index of Series in Pandas?
How do you reset index of Series in Pandas?

Time:11-08

After using value_counts in Pandas I want to reset the index but the first column's name is replace with 'index' and every columns' name got pushed to the right

df = df[df['type']=='food']['fruit'].value_counts()
df = df.reset_index()
df

  index  fruit
0 apple  120
1 grape  110
2 orange 30


maybe I can use df.columns to rename colums but is there anyway to prevent 'index' replacing fist column's name? this is what i want

  fruit  number
0 apple  120
1 grape  110
2 orange 30

CodePudding user response:

You can use rename_axis to rename the index and the name parameter of reset_index:

(df[df['type']=='food']['fruit'].value_counts()
 .rename_axis('fruit')
 .reset_index(name='number'))

Other option, use groupby.agg:

(df[df['type']=='food']
 .groupby('fruit', as_index=False)
 .agg(number=('fruit', 'count'))
)

output:

    fruit  number
0   Apple       2
1  Banana       1

Used input:

   type   fruit
0  food   Apple
1  food   Apple
2  food  Banana

CodePudding user response:

You can use reset_index(name=...) and pandas.DataFrame.rename.

df = df[df['type']=='food']['fruit'].value_counts()
df = df.reset_index(name='number').rename(columns={'index': 'fruit'})
print(df)

Output:

    fruit  number
0   apple       2
1   grape       1
2  orange       1

Input DataFrame:

   type   fruit
0  food   apple
1  food   apple
2  food   grape
3  food  orange
  • Related