0

I need to set index to my rows, and when I do that, pandas automatically makes my column index hierarchical..and then I tried every flatten mathod I can search, but once I reset_index, my index for row are replaced with iloc (integers). If I use df.columns = [ my col index name], it doesn't flatten my columns' index at all..

I use pandas official docs as example

df = pd.DataFrame({'month': [1, 4, 7, 10],
                   'year': [2012, 2014, 2013, 2014],
                   'sale': [55, 40, 84, 31]})
df.set_index('month')

and I get

       year  sale
month
1      2012    55
4      2014    40
7      2013    84
10     2014    31

Then I flatten the index by

df.reset_index()

Then it becomes

  index month   year    sale
0   0   1       2012    55
1   1   4       2014    40
2   2   7       2013    84
3   3   10      2014    31

(The month for row index disappeard...) This really kills me so Im appreciate it if someone can help to make the dataframe to sth like

month  year  sale
1      2012    55
4      2014    40
7      2013    84
10     2014    31

Thanks!

1 Answers1

1

You only need to

df.reset_index(drop=True)

which returns

  month  year  sale
0      1  2012    55
1      4  2014    40
2      7  2013    84
3     10  2014    31
  • Yah I did that! But I also want my rows indexed by month...so I have to do set_index again and it gives me the unwanted col index... – zhuang vapeur Dec 03 '20 at 09:32