I am trying to add a subheader to a pandas data frame based on some attributes. an example is the following:
Currently, I have all of the attributes in the second row but would like to add a header/above row based on a grouping of certain attributes.
Note: The main key is the order ID not sure if that helps.
CodePudding user response:
import pandas as pd
cols = pd.MultiIndex.from_tuples([("Buyer details", "Buyer Name"),
("Buyer details", "Buyer Address"),
("Oder Details", "Order Id"),
("Oder Details", "Order description"),
("Oder Details", "Order person"),
("Item Details", "Item Link"),
("Item Details", "Item cost")])
df = pd.DataFrame(columns=cols)
print(df)
CodePudding user response:
I assume you already have a dataframe with the column names in the inner level shown in your picture. Then one way to do without knowing the column names is:
cols = df.columns
df.columns = pd.MultiIndex.from_arrays(
[[''] * len(cols), cols]).map(lambda x: (x[1].split()[0] ' details', x[1]))