Reputation: 67
stocks= ['Apple','Raytheon','Amazon']
df = pd.DataFrame(data=[[10,11,12,13,5,2],[5,6,7,7,7,1]],
columns=['2020-12-31','2019-12-31','2020-09-26','2019-09-28','2020-01-01','2019-01-01'], index=['cash','inventory'])
I have this list of stocks and their balance sheets in a dataframe. I would like to group the first 2 columns(2020-12-31,2019-12-31) under Apple, the next two columns under Raytheon and the last two under Amazon.
How to achieve this in Python?
Upvotes: 0
Views: 60
Reputation: 35646
Try scaling the stocks
list up with np.repeat
then zip
and use MultiIndex.from_tuples
:
df.columns = pd.MultiIndex.from_tuples(zip(np.repeat(stocks, 2), df.columns))
df
:
Apple Raytheon Amazon
2020-12-31 2019-12-31 2020-09-26 2019-09-28 2020-01-01 2019-01-01
cash 10 11 12 13 5 2
inventory 5 6 7 7 7 1
Upvotes: 1