Darth.Vader Darth.Vader - 13 days ago 5
Python Question

pandas dataframe sum with groupby

I have a pandas dataframe that structurally looks like this:

[
['x', '1', '-7']
['x', '2', '-2']
['y', '3', '-1']
['y', '4', '-3']
]


I have to groupby the first column (with values
x
and
y
s) and find the sum for the second and third column for each
x
and
y
like this:

[
['x', 3, -9]
['y', 7, -4]
]


How can I do this using pandas?

Answer

setup
I converted your string numbers to actual numbers

df = pd.DataFrame(
    [
        ['x', '1', '-7'],
        ['x', '2', '-2'],
        ['y', '3', '-1'],
        ['y', '4', '-3']
    ]
)

df[1] = pd.to_numeric(df[1])
df[2] = pd.to_numeric(df[2])

solution

df.groupby(0).sum()

enter image description here