我有一个两列的 pandas DataFrame,如下所示:
import pandas as pd
df = pd.DataFrame([[5,100],[6,200],[7,250],[8,1000]],columns=['Price','Units'])
给定一个阈值,比如 1500,我想取两列乘积的累积和(直到总数达到阈值 1500),然后除以“单位”列的累积和,例如累计和只有 1500。我可以使用 for 循环来实现这个,但是 Pandas 会怎么做呢?
稍微说明一下细节:
df['Product'] = df.prod(axis=1)
df['CumSum'] = df['Product'].cumsum()
在索引=1时,累计和超过阈值(1700 > 1500)。然后,我们只想获取达到阈值的单位数量。例如,结果将是 df:
Price Units Product CumSum CumSumWithThreshold
5 100 500 500 500
6 200 1200 1700 1500
7 250 1750 3450 0
8 1000 8000 11450 0
假设您有 1500 美元可花,每单位的平均价格是多少?在上面的例子中,您可以购买 100 个价格为 5 美元的单位(总计 500 美元)和(1000/6)个单位的价格为 6 美元(按此价格总计 1000 美元)。因此,每单位的平均价格为:$1500/(100 + (1000/6)) = $5.625...
最佳答案
我假设这是您尝试过的 for 循环类型,但这不需要在终止行之外进行任何计算。
import pandas as pd
df = pd.DataFrame([[5,100],[6,200],[7,250],[8,1000]],columns=['Price','Units'])
def average_price_to_buy_thresh(df, thresh):
total = thresh
units = 0
for i, (px, amt) in df.iterrows():
prod = px*amt
if prod<total:
units += amt
total -= prod
else:
units += total/px
return (thresh/units)
print('Result: $%.2f' % average_price_to_buy_thresh(df, 1500))
关于python - 累计金额达到阈值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48447641/