I have following dataframe
And I want to convert it into the following format:-
To do so I have used the following code snippet:-
df = pd.wide_to_long(df, stubnames=['manufacturing_unit_','outlet_','inventory','year'],i=['Brand','customer name','Factory'],j='drop').reset_index().drop('drop', 1)
But we are getting below errors::
1) ValueError: stubname can't be identical to a column name
2) the id variables need to uniquely identify each row
You can use numpy concatenate
like that:
res = pd.DataFrame(pd.np.concatenate([df.iloc[:,[0,1,2,3,6,9,12]], df.iloc[:,[0,1,2,4,7,10,13]], df.iloc[:,[0,1,2,5,8,11,14]]]))
res.columns = ['Brand', 'customer name', 'Factory', 'manufacturing', 'outlet', 'inventory', 'year']
Update for variable number of column names (e.g. 1...3):
cols = [f'Brand|customer name|Factory|{x}$' for x in range(1,4)]
pd.DataFrame(pd.np.concatenate([df.filter(regex=col) for col in cols]))