簡體   English   中英

pandas 在 pivot_table 期間聚合多個列

[英]pandas aggregate multiple columns during pivot_table

有一個 dataframe 像這樣:

df = pd.DataFrame((['1990-01-01','A','S1','2','string2','string3'],
 ['1990-01-01','A','S2','1','string1','string4'],
 ['1990-01-01','A','S3','1','string5','string6']),columns= 
 ["date","type","status","count","s1","s2")


           date type status count       s1       s2
 0  1990-01-01    A     S1     2  string2  string3
 1  1990-01-01    A     S2     1  string1  string4
 2  1990-01-01    A     S3     1  string5  string6
 ...

我想得到以下結果(每個日期和每種類型都應該有單行,並獲取 s1 列的最小值,獲取 s2 列的最大值)

date             type       S1    S2   S3    min_s1        max_s2
1990-01-01       A           2     1   1     string1      string6

我嘗試使用pivot_table

df.pivot_table(index=['date','type'],columns=['status'],values=['count','s1','s2'], aggfunc={
'count':np.sum, 
's1': np.min,
's2': np.max
})

但這只會得到下面的結果,這會導致多列而不是最終結果。

                count             s1                         s2
status             S1 S2 S3       S1       S2       S3       S1       S2       S3
date       type
1990-01-01 A        2  1  1  string2  string1  string5  string3  string4  string6

有人知道嗎? 謝謝。

看起來你想結合pivotgroupby.agg

(df.pivot(index=['date','type'],columns='status', values='count')
   .join(df.groupby(['date', 'type']).agg({'s1': 'min', 's2': 'max'}))
   .reset_index()
)

output:

         date type S1 S2 S3       s1       s2
0  1990-01-01    A  2  1  1  string1  string6

暫無
暫無

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

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