equanimity
equanimity

Reputation: 2533

How to "flatten" a Pandas dataframe?

I have a Pandas dataframe df that looks as follows:

                                                 Expenses
date           manufacturer     department      
2021.01.03     Mercedes         Service          541
                                Sales            879
                                Marketing        134
2021.01.04     Mercedes         Service          471
                                Sales            193
                                Marketing        302
2021.01.05     Mercedes         Service          938
                                Sales            183
                                Marketing        193
  

Notice that Expenses is on a higher level than date, manufacturer, and department.

When I call df.columns, I see the following:

Index(['Expenses'], dtype='object)

I was expecting to see a list containing Expenses, date, manufacturer, and department. Something as follows:

df.columns.values.tolist()
['Expenses', 'date', 'manufacturer', 'department']
<class 'list'>

How would I "flatten" this dataframe so that Expenses, date, manufacturer, and department are all treated as columns on the same level?

Thanks in advance!

Upvotes: 0

Views: 1623

Answers (1)

GabrielP
GabrielP

Reputation: 782

If 'date', 'manufacturer' and 'department' are part of the index. This might help you:

df = df.reset_index()

Upvotes: 2

Related Questions