简体   繁体   English

根据某些列向 pandas dataframe 添加标题/另一行

[英]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.

相关问题 将值添加到基于另一个 dataframe 的 pandas dataframe 列 - adding values to pandas dataframe columns based on another dataframe 根据另一列的值将列添加到pandas数据框中 - Adding columns to a pandas dataframe based on values of another column Pandas Dataframe 更新列基于将其他一些列与另一个具有不同列数的 dataframe 的列进行比较 - Pandas Dataframe updating a column based comparing some other columns with the columns of another dataframe with different number of columns 将标题名称添加到熊猫数据框中的一组列? - Adding a header name to a group of columns in a dataframe in pandas? 合并 pandas dataframe 最后一行中的一些列 - Combine some columns in last row of a pandas dataframe 基于列标题的 Pandas Dataframe 总和行 - Pandas Dataframe sum row based on column header 在 python pandas Z6A8064B5DF479455500553C47C550 中的 header 列上方添加一行 - Adding a row above header columns in python pandas dataframe, without any file read/write 通过将行熊猫中的NaN值与列匹配来将数据帧中的一行添加到另一行中 - Adding a row from a dataframe into another by matching columns with NaN values in row pandas python 熊猫数据框基于标签添加新列 - pandas dataframe adding new columns based on labels 基于其他列向 pandas dataframe 添加列 - Adding a column to a pandas dataframe based on other columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM