亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

python 數據透視表中的總值

python 數據透視表中的總值

慕哥9229398 2023-05-23 10:41:12
我的原始數據框類似于下面的數據框:df= pd.DataFrame({'Variation' : ['A']*5 + ['B']*3 + ['A']*4,                   'id': [11]*4 + [12] + [15]*2 + [17] + [20]*4,                 'steps' : ['start','step1','step2','end','end','step1','step2','step1','start','step1','step2','end']})我想從這個數據框創建一個數據透視表,我使用了下面提到的代碼:df1=df.pivot_table(index=['Variation'], columns=['steps'],                           values='id', aggfunc='count', fill_value=0)但是,我也想查看 id 的總不同計數。有人可以讓我知道如何實現這一目標嗎?我的預期輸出應該是:| Variation | Total id | Total start | Total step1 | Total step2 | Total end ||-----------|----------|-------------|-------------|-------------|-----------|| A         | 3        | 2           | 2           | 2           | 3         || B         | 2        | 0           | 2           | 1           | 0         |
查看完整描述

1 回答

?
牛魔王的故事

TA貢獻1830條經驗 獲得超3個贊

使用SeriesGroupBy.nunique

df1 = df1.join(df.groupby('Variation')['id'].nunique().rename('Total id'))

print(df1)

? ? ? ? ? ?end? start? step1? step2? Total id

Variation? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

A? ? ? ? ? ? 3? ? ? 2? ? ? 2? ? ? 2? ? ? ? ?3

B? ? ? ? ? ? 0? ? ? 0? ? ? 2? ? ? 1? ? ? ? ?2

如果之后需要列Variation:


c = ['id'] + df['steps'].unique().tolist()

df1 = (df1.join(df.groupby('Variation')['id'].nunique())

? ? ? ? ? .reindex(columns=c)

? ? ? ? ? .add_prefix('Total ')

? ? ? ? ? .reset_index()

? ? ? ? ? .rename_axis(None, axis=1))


print(df1)

? Variation? Total id? Total start? Total step1? Total step2? Total end

0? ? ? ? ?A? ? ? ? ?3? ? ? ? ? ? 2? ? ? ? ? ? 2? ? ? ? ? ? 2? ? ? ? ? 3

1? ? ? ? ?B? ? ? ? ?2? ? ? ? ? ? 0? ? ? ? ? ? 2? ? ? ? ? ? 1? ? ? ? ? 0


查看完整回答
反對 回復 2023-05-23
  • 1 回答
  • 0 關注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號