简体   繁体   中英

Adding a header/another row to a pandas dataframe based on some columns

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.

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)

在此处输入图像描述

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]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM