为了账号安全,请及时绑定邮箱和手机立即绑定

从 Panda 中的列中获取位于前 n% 的值的百分比,例如 25%、50% 等或低于 n%

从 Panda 中的列中获取位于前 n% 的值的百分比,例如 25%、50% 等或低于 n%

小怪兽爱吃肉 2022-10-06 17:03:02
我有一个这样的数据框 -我想要表格中这样的列-所以决赛桌是这样的——我如何计算这些列。我在 django rest API 中有当前代码-@api_view(['GET','POST'])def sale_prod(request):       if request.method == 'GET':    data = sales_products.objects.values()    df = pd.DataFrame(data)    df = df.groupby(['item_id','item_code'])['amount','quantity'].sum().reset_index()    df.dropna(inplace=True)    df['amount_per'] = (df.amount / df.amount.sum())*100          # revenue contribution    df['quantity_per'] = (df.quantity / df.quantity.sum())*100    # unit sold contribution    df = df.round({'quantity': 0, 'amount':2, 'amount_per':2, 'quantity_per':2})    main_list = []    for ind in df.index:        dict1 = {}        dict1['item_code'] = df['item_code'][ind]        dict1['amount'] = df['amount'][ind]        dict1['quantity'] = df['quantity'][ind]        dict1['amount_per'] = df['amount_per'][ind]        dict1['quantity_per'] = df['quantity_per'][ind]        main_list.append(dict1)    return Response(main_list)这段代码以数据框的形式给了我输出 -amount_per = 按金额计算的项目贡献百分比quantity_per = 按数量计算的项目贡献百分比请帮我找出正确的答案。
查看完整描述

1 回答

?
神不在的星期二

TA贡献1963条经验 获得超6个赞

您正在寻找df.quantile和一些基本数学。

在表中显示这些值并没有多大价值——它的 3 列以上乘以len(df)数据都是一样的——所以我将它们作为简单的语句给出:

import pandas as pd

import random


# some data shuffling to see it works on unsorted data

random.seed(42)

data = [[f"product {i+1:3d}",i*10] for i in range(100)]

random.shuffle(data)


df = pd.DataFrame(data, columns=['name', 'price']) 


# calculate the quantile series

q25 = df.quantile(.25, numeric_only=True)

q50 = df.quantile(.5, numeric_only=True)

q75 = df.quantile(.75, numeric_only=True)


print (q25, q50, q75, sep="\n\n")


print( f"Bottom 25% of prices are below/equal to {q25.price} thats", end=" ") 

print( f"{len(df[df.price <= q25.price]) / (len(df) / 100)}% of all items")


print( f"Bottom 50% of prices are below/equal to {q50.price} thats", end=" ")

print( f"{len(df[df.price <= q50.price]) / (len(df) / 100)}% of all items")


print( f"Bottom 75% of prices are below/equal to {q75.price} thats", end= " ")

print( f"{len(df[df.price <= q75.price]) / (len(df)/ 100)}% of all items")

(未洗牌)数据框看起来像


           name  price

0   product   1      0

1   product   2     10

2   product   3     20 

..          ...    ...  

97  product  98    970

98  product  99    980

99  product 100    990


[100 rows x 2 columns]

输出:


price    247.5

Name: 0.25, dtype: float64


price    495.0

Name: 0.5, dtype: float64


price    742.5

Name: 0.75, dtype: float64


Bottom 25% of prices are below/equal to 247.5 thats 25.0% of all items

Bottom 50% of prices are below/equal to 495.0 thats 50.0% of all items

Bottom 75% of prices are below/equal to 742.5 thats 75.0% of all items


查看完整回答
反对 回复 2022-10-06
  • 1 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信