[英]How to add a new row with new header information in same dataframe
[英]Add new row as header in multiIndexed dataframe
我有一個包含天、年、a1、a2、b1 列的數據框。
我嘗試了多索引和數據透視表以這種格式創建標題。但無法以這種格式生成 o/p。
table = pd.pivot_table(df, index=['days'],
columns=['year'], fill_value=0)
print(table)
多索引
unique_kpis = df["year"].unique()
l = ['a1', 'a2', 'b1']
header = pd.MultiIndex.from_product([unique_kpis,
l],
names=['year','days']).to_list()
輸入數據:
[{'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}]
首先使用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.