[英]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.我正在尝试根据某些属性向 pandas 数据帧添加子标题。 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.注意:主要关键是订单 ID,不确定是否有帮助。
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.我假设您已经有一个 dataframe ,其内部级别的列名显示在您的图片中。 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]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.