![](/img/trans.png)
[英]How to use groupby in pandas to calculate a percentage / proportion total based on a criteria in another column
[英]split a pandas column based on value proportion from the total
我正在嘗試根據每行對總數的貢獻從更大的列表中創建一個列表。 我希望列表包括占總數 40% 的“頂部”行
每行對應於總數的百分比。 例如,第一個列表必須包括累計總計占“總數”40% 的行。 “總計”是列中所有行的總和。
list = [0.2, 0.25, 0.15, 0.1, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05]
我想得到:
list1 = [0.2, 0.25, 0.15, 0.1]
因為列表 1 中的值是列表中的最大值,它們占列表的 40%。
我該如何編寫 python 代碼來做到這一點?
我不知道如何繼續,我看過的所有資源都教如何根據固定值進行拆分,但我沒有看到關於列表中值總和的基於分類的貢獻百分比。
我想知道是否有人知道我可以使用什么 function,或者我該如何繼續。 預先感謝您的任何幫助。
你可以試試這個:
import math
list0
# Out[75]: [0.2, 0.25, 0.15, 0.1, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05]
list1 = sorted(list0)[-(math.ceil(len(list0)*0.4)):]
list1
# Out[79]: [0.1, 0.15, 0.2, 0.25]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.