我为这个含糊的标题道歉,很难将我想要的翻译成书面形式。
我正在尝试构建一个填充的折线图,其中日期在x轴上,总交易量在y轴上。
我的数据
该对象是一个pandas数据帧。
date | symbol | type | qty | total
----------------------------------------------
2020-09-10 ABC Buy 5 10
2020-10-18 ABC Buy 2 20
2020-09-19 ABC Sell 3 15
2020-11-05 XYZ Buy 10 8
2020-12-03 XYZ Buy 10 9
2020-12-05 ABC Buy 2 5 我想要什么
date | symbol | type | qty | total | aggregate_total
------------------------------------------------------------
2020-09-10 ABC Buy 5 10 10
2020-10-18 ABC Buy 2 20 10+20 = 30
2020-09-19 ABC Sell 3 15 10+20-15 = 15
2020-11-05 XYZ Buy 10 8 8
2020-12-03 XYZ Buy 10 9 8+9 = 17
2020-12-05 ABC Buy 2 5 10+20-15+5 = 20我现在所处的位置
我正在使用两个嵌套的for循环:一个用于迭代符号,一个用于迭代每一行。我将临时结果存储在列表中。我仍然不确定如何将结果添加到最终的数据帧中。我可以按符号和日期对数据帧重新排序,然后将每个临时列表附加在一起,最后将该临时列表分配到一个新列。
下面的代码只是行上的内部循环。
af = df.loc[df['symbol'] == 'ABC']
for i in (range(0,af.shape[0])):
# print(af.iloc[0:i,[2,4]])
# if type is a buy, we add the last operation to the aggregate
if af.iloc[i,2] == "BUY":
temp_agg_total.append(temp_agg_total[i] + af.iloc[i,4])
temp_agg_qty.append(temp_agg_qty[i] + af.iloc[i, 3])
else:
temp_agg_total.append(temp_agg_total[i] - af.iloc[i,4])
temp_agg_qty.append(temp_agg_qty[i] - af.iloc[i, 3])
# Remove first element of list (0)
temp_agg_total.pop(0)
temp_agg_qty.pop(0)
af = af.assign(agg_total = temp_agg_total,
agg_qty = temp_agg_qty)我的问题
有没有更好的方法在pandas或numpy中做到这一点?对于相对简单的东西来说,它感觉真的很重。
Buy/Sell类型的操作的出现使事情变得复杂。
问候
发布于 2020-12-07 00:13:59
# negate qty of Sells
df.loc[df['type']=='Sell', 'total'] *=-1
# cumulative sum of the qty based on symbol
df['aggregate_total'] = df.groupby('symbol')['total'].cumsum()发布于 2020-12-07 00:12:22
这就是你要找的东西吗?
df['Agg'] = 1
df.loc[df['type'] == 'Sell', 'Agg'] = -1
df['Agg'] = df['Agg']*df['total']
df['Agg'].cumsum()发布于 2020-12-07 00:13:24
df["Type_num"] = df["type"].map({"Buy":1,"Sell":-1})
df["Num"] = df.Type_num*df.total
df.groupby(["symbol"],as_index=False)["Num"].cumsum()
pd.concat([df,df.groupby(["symbol"],as_index=False)["Num"].cumsum()],axis=1)
date symbol type qty total Type_num Num CumNum
0 2020-09-10 ABC Buy 5 10 1 10 10
1 2020-10-18 ABC Buy 2 20 1 20 30
2 2020-09-19 ABC Sell 3 15 -1 -15 15
3 2020-11-05 XYZ Buy 10 8 1 8 8
4 2020-12-03 XYZ Buy 10 9 1 9 17
5 2020-12-05 ABC Buy 2 5 1 5 20这里最重要的是累计和。重新分组用于确保仅在每种不同的symbol上执行累积和。列的重命名和删除对您来说应该很容易。
诀窍是我把{sell; buy}变成了{1,-1}
https://stackoverflow.com/questions/65170010
复制相似问题