pandas中dataframe的apply按行操作
1. 读取数据
假设存在如下原始数据
dataframe=pd.DataFrame({'stock_name':['Leetcode','CoronaMasks','Leetcode','Handbags','CoronaMasks','CoronaMasks','CoronaMasks','CoronaMasks','Handbags','CoronaMasks',],
'operation':['Buy','Buy','Sell','Buy','Sell','Buy','Sell','Buy','Sell','Sell',],
'price':[1000,10,9000,30000,1010,1000,500,1000,7000,10000,]
})
其中,stock_name是股票名称;operation是对该股票进行买进或者卖出,其中Buy是买进,Sell是卖出,买入和卖出对应了资金的流入和流出;price是对股票操作时候的金额。
2. 操作数据
dataframe['capital_gain_loss']=dataframe[['operation','price']].apply(lambda x:-x[1] if x[0]=='Buy' else x[1],axis=1) dataframe_stock=dataframe.groupby(['stock_name'],as_index=False).aggregate({'capital_gain_loss':'sum'})
假设operation字段中的Buy时capital_gain_loss为负的price,而operation字段中的Sell时capital_gain_loss为正的price。这样的话,capital_gain_loss需要operation和price两个字段来确定,也即是apply按行操作,axis=1。
当apply按行操作之后,再对每个stock_name下的资本收益capital_gain_loss求和。该求和不使用stock_name作为index,也即是as_index=False。