0

I am trying to add a subheader to a pandas data frame based on some attributes. an example is the following:

Current input (already a dataframe with data generated): enter image description here

Ideal output: enter image description here 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.

2 Answers 2

1

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]))
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much and yes I have a df. but instead of having it with the details, is there a way to manually add in the column names? I have just showed an example in the question, but I actually have around 40 columns and not all of the grouping ends in "details".
Yes if you give the right input and right output, better answer can be provided.
I have updated. Please let me know if I could provide more clarity
Do you have a mapping(sort of a dict) like {'SKU Details': ['Product Name', 'SKU Code', 'SKU Expiration Date']} ?
0
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)

enter image description here

1 Comment

Thank you, I have an existing data frame with columns of the second header, and want to group based on the first. is there a way to do that?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.