I'm a novice in python&pandas, could you please advise me if it is possible to ungroup and unpivot such dataframe?
The groups in source data are in the only column marked by prefix spaces and look like
import pandas as pd
import numpy
df = pd.DataFrame([
['Costs', numpy.nan, numpy.nan, numpy.nan],
[' Vehicles', numpy.nan, numpy.nan, numpy.nan],
[' Cars', numpy.nan, numpy.nan, numpy.nan],
[' BMW', 1000, 1100, 1010],
[' Toyota', 1203, 1302, 1322],
[' Cars - Total', 2203, 2402, 2332],
[' Trucks', numpy.nan, numpy.nan, numpy.nan],
[' Volvo', 5000, 5001, 5010],
[' MAN', 5500, 5055, 5066],
[' Trucks - Total', 10500, 10056, 10076],
[' Vehicles - Total', 12703, 12458, 12408],
[' Crew', numpy.nan, numpy.nan, numpy.nan],
[' Gomez Addams', 10000, 10000, 10000],
[' Morticia Addams', 10000, 10000, 10000],
[' Crew - Total', 20000, 20000, 20000],
['Costs - Total', 32703, 32458, 32408],
],
columns=['Level', 'Q1_2019', 'Q2_2019', 'Q3_2019'])
I need to convert it to a table like
Level, Sublevel1, Sublevel2, Sublevel3, Sublevel4, Date, Value
"Costs", "Vehicles", "Cars", "BMW", "Q1_2019", 1000
"Costs", "Crew", "Gomez Addams", , "Q1_2019", 10000
For now I've creates extra "Sublevel" columns, backfilled them by regex, then fill the Sublevels gaps row-by-row, then apply melt(). Can it be done more pythonish?