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

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

按中位數、百分位數和占總數的百分比分組

按中位數、百分位數和占總數的百分比分組

絕地無雙 2023-02-22 15:14:59
我有一個看起來像這樣的數據框...... ID Acuity TOTAL_ED_LOS 1    2      423 2    5      52 3    5      535 4    1      87 ...我想生成一個如下所示的表: Acuity    Count   Median Percentile_25   Percentile_75   % of total   1         234 ...                                         31%                                            2         65 ...                                           8%   3         56 ...                                           7%   4         345 ...                                          47%   5         35  ...                                          5%我已經有代碼可以提供我需要的一切,除了 % of total 列def percentile(n):    def percentile_(x):        return np.percentile(x, n)    percentile_.__name__ = 'percentile_%s' % n    return percentile_df_grp = df_merged_v1.groupby(['Acuity'])df_grp['TOTAL_ED_LOS'].agg(['count','median',                                   percentile(25), percentile(75)]).reset_index()有沒有一種有效的方法可以添加總列的百分比?下面的鏈接包含有關如何獲取總數百分比的代碼,但我不確定如何將其應用到我的代碼中。我知道我可以創建兩個表然后合并它們,但我很好奇是否有更簡潔的方法。如何在 Python 中計算 groupby 中的計數和百分比
查看完整描述

1 回答

?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

這是使用一些 pandas 內置工具的一種方法:


# Set random number seeed and create a dummy datafame with two columns

np.random.seed(123)

df = pd.DataFrame({'activity':np.random.choice([*'ABCDE'], 40), 

                   'TOTAL_ED_LDS':np.random.randint(50, 500, 40)})


# Reshape dataframe to get activit per column 

# then use the output from describe and transpose

df_out = df.set_index([df.groupby('activity').cumcount(),'activity'])['TOTAL_ED_LDS']\

           .unstack().describe().T


#Calculate percent count of total count

df_out['% of Total'] = df_out['count'] / df_out['count'].sum() * 100.

df_out

輸出:


          count        mean         std    min     25%    50%     75%    max  % of Total

activity                                                                                

A           8.0  213.125000  106.810162   93.0  159.50  200.0  231.75  421.0        20.0

B          10.0  308.200000  116.105125   68.0  240.75  324.5  376.25  461.0        25.0

C           6.0  277.666667  117.188168  114.0  193.25  311.5  352.50  409.0        15.0

D           7.0  370.285714  124.724649  120.0  337.50  407.0  456.00  478.0        17.5

E           9.0  297.000000  160.812002   51.0  233.00  294.0  415.00  488.0        22.5



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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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