Skip to content
Advertisement

Pandas equivalent for SQL – arithmetic expression within aggregate function

I am a pandas newbie coming from a SQL background although have some exposure to Python.

I was wondering if there is a simple way to do the following SQL code in pandas dataframe:

Select
  A,
  Sum(B/C) value
From
  Table
Group by
  A

Below is all I got so far there doesn’t seem to be a syntax to include arithmetic expressions:

df.groupby(['A']).sum()

Thanks in advance.

Advertisement

Answer

try this,

df.assign(value = df.B.div(df.C)).groupby('A')['value'].sum()
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement