简体   繁体   English

在多索引数据框中添加新行作为标题

[英]Add new row as header in multiIndexed dataframe

I have a dataframe which has days, year, a1, a2, b1 columns.我有一个包含天、年、a1、a2、b1 列的数据框。

在此处输入图片说明

I want to create excel like in this format我想以这种格式创建excel 在此处输入图片说明

I tried multiindexing and pivot table to create header in this format.but not able to generate o/p in this format.我尝试了多索引和数据透视表以这种格式创建标题。但无法以这种格式生成 o/p。

table = pd.pivot_table(df,  index=['days'],
                columns=['year'], fill_value=0)
print(table)

with multiindexing多索引

unique_kpis = df["year"].unique()
l = ['a1', 'a2', 'b1']
header = pd.MultiIndex.from_product([unique_kpis,
                                 l],
                                names=['year','days']).to_list()

Input data:输入数据:

[{'days': 1, 'year': 'A', 'a1': 1001, 'a2': 1002, 'b1': 45}, {'days': 2, 'year': 'B', 'a1': 452, 'a2': 453, 'b1': 345}, {'days': 3, 'year': 'A', 'a1': 1001, 'a2': 10, 'b1': 34}, {'days': 4, 'year': 'B', 'a1': 3456, 'a2': 453, 'b1': 345}, {'days': 5, 'year': 'A', 'a1': 1003, 'a2': 123, 'b1': 34}, {'days': 6, 'year': 'B', 'a1': 3456, 'a2': 453, 'b1': 345}]

Use DataFrame.sort_index first and then create tuples for new level:首先使用DataFrame.sort_index ,然后为新级别创建元组:

print (df)
   days year  a1  a2  b1
0     1    A   4   5   4
1     2    A   7   5   4
2     1    B   8   2   0
3     2    B   9   5   1


table = pd.pivot_table(df,  index=['days'],
                columns=['year'], fill_value=0).sort_index(axis=1, level=1)

table.columns = pd.MultiIndex.from_tuples([(b, f'Total {a[0].upper()}', a) 
                                           for a, b in table.columns])
print (table)
           A                  B           
     Total A    Total B Total A    Total B
          a1 a2      b1      a1 a2      b1
days                                      
1          4  5       4       8  2       0
2          7  5       4       9  5       1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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