Python Groupby函数

2024-05-16 13:13:04 发布

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

我试图使用Pandas中的groupby函数来计算使用groupby函数进行的买卖数量的差异

我尝试了很多不同的方法,但都没有找到解决办法

df = pd.DataFrame({'Security Name':['Max Pro','Max Pro','AVG','AVG'],
                   'Bos':['Buy','Sell','Buy','Sell'],
                    'Quantity Traded': [2000,1500,500,2000]
                  })

    # This is the output I get
       Security Name       Bos            Quantity Traded
    0    Max Pro           Buy               2000
    1    Max Pro           Sell              1500
    2    AVG               Buy               500
    3    AVG               Sell              2000
gb = df.groupby('Security Name')

使用groupby函数所需的输出-

   Security Name          Diff_in_Traded_Quantity
  0  Max Pro                    500
  1  AVG                       -1500

无法获取上述结果。尝试了apply和agg()函数,但无法解决此问题

我需要帮助


Tags: 函数namepandasdf数量buymaxquantity
2条回答

从你的例子中我了解到,Bos == "Buy"Quantity Traded损失,而Bos == "Sell"Quantity Traded增益。考虑到这一点,您可以执行以下操作:

df = pd.DataFrame({
    'Security Name':['Max Pro','Max Pro','AVG','AVG'] ,
    'Bos':['Buy','Sell','Buy','Sell'],
    'Quantity Traded': [2000,1500,500,2000]
})

# Set the Bos == Sell as negative values
df.loc[ df["Bos"] == "Sell", "Quantity Traded" ] *= -1 
df = df.groupby("Security Name").sum()

似乎您需要^{}groupby

df['Quantity Traded'].diff().groupby(df['Security Name'],sort=False).last()

Security Name
Max Pro    -500.0
AVG        1500.0

相关问题 更多 >