如果为负,则使用加权平均值

2024-06-11 15:18:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧:

a = {'Price': [10, 15, 20, 25, 30], 'Total': [10000, 12000, 15000, 14000, 10000],
 'Previous Quarter': [0, 10000, 12000, 15000, 14000]}
a = pd.DataFrame(a)
print (a)

有了这些原始数据,我添加了许多附加列,包括加权平均价格(WAP)

a['Change'] = a['Total'] - a['Previous Quarter']
a['Amount'] = a['Price']*a['Change']
a['Cum Sum Amount'] = np.cumsum(a['Amount'])
a['WAP'] = a['Cum Sum Amount'] / a['Total']

这是很好的,但是,由于总量开始减少,这会降低加权平均价格。你知道吗

我的问题是,如果总数减少,我将如何让WAP反映上述行?例如,在第3行中,Total是1000,比第2行低。这使WAP从12.6降到了11.78,但我希望它是12.6而不是11.78。你知道吗

我尝试过在['Total']<;0中循环,然后在['WAP']=0中循环,但这会影响整个列。你知道吗

最后,我要找一个WAP专栏,上面写着: 10、10.83、12.6、12.6、12.6


Tags: 数据dataframe原始数据changeamountpricetotalpd
2条回答

您可以使用^{}

a['WAP'] = (a['Cum Sum Amount'] / a['Total']).cummax()

print (a['WAP'])

0    10.000000
1    10.833333
2    12.666667
3    12.666667
4    12.666667
Name: WAP, dtype: float64

作为一个完全的Python初学者,我可以考虑以下两种选择

或者

a['WAP'] = np.maximum.accumulate(a['Cum Sum Amount'] / a['Total'])

或者在您已经创建了WAP之后,您可以使用diff方法只修改子集(感谢@ayhan提供了loc,它将修改a

a.loc[a['WAP'].diff() < 0, 'WAP'] = max(a['WAP'])

相关问题 更多 >