簡體   English   中英

如何使 Pandas 中的數據透視表表現得像 Excel 中的數據透視表?

[英]How to make pivot table in pandas behaves like pivot table in Excel?

我正在嘗試轉置數據,聚合方法無關緊要,但數據按值而不是日期分組

代碼:

import pandas as pd
d = {'date': ['2/21/2020', '2/21/2020','2/22/2020','2/22/2020','2/23/2020','2/23/2020'], 
     'name': ['James','John', 'James','John','James','John'],
     'A':[1,2,3,4,5,6],
     'B':[7,8,9,10,11,12],
     'C':[13,14,15,16,17,18]}
df = pd.DataFrame(data=d)
df = pd.pivot_table (df, index ='name', columns='date', values=['A','B','C'])
df

我得到的輸出:

熊貓數據框

我需要的

Excel 數據透視表

注意:從 Excel 中,數據透視表輸入為(“日期”作為列/“名稱”作為行/“A”、“B”和“C”作為值)

您需要使用swaplevel來切換列 MultiIndex 的順序,以便日期在頂部,“A”、“B”、“C”在底部。 然后,您還將對該索引進行排序。 要將“A”替換為“A 之和”,我使用rename方法為列添加了“Sum of” 前綴。

new_df = (df.pivot_table(index ='name', columns='date', values=['A','B','C'])
          .swaplevel(axis=1)
          .sort_index(axis=1)
          .rename(columns="Sum of {}".format, level=1)
)

print(new_df)
date  2/21/2020                   2/22/2020                   2/23/2020                  
       Sum of A Sum of B Sum of C  Sum of A Sum of B Sum of C  Sum of A Sum of B Sum of C
name                                                                                     
James         1        7       13         3        9       15         5       11       17
John          2        8       14         4       10       16         6       12       18

為了獲得類似的輸出,我們可以使用marginsswaplevel 之后,我們可以使用mapper重命名列。 最后, .iloc[:, :-3]用於刪除額外的行邊距,如果您想要行邊距,可以刪除。

df1 = (df.pivot( index=['name'],  columns = 'date', margins=True, margins_name='Grand Total',  aggfunc=np.sum)
      .swaplevel(axis=1)
      .sort_index(axis=1)
      .rename(mapper=lambda x: f'Sum of {x}',axis=1,level=1)
      .iloc[:, :-3])


print(df1)

輸出:

date        2/21/2020                   2/22/2020                   2/23/2020                  
             Sum of A Sum of B Sum of C  Sum of A Sum of B Sum of C  Sum of A Sum of B Sum of C
name                                                                                           
James               1        7       13         3        9       15         5       11       17
John                2        8       14         4       10       16         6       12       18
Grand Total         3       15       27         7       19       31        11       23       35

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM