Heisenberg - 26 days ago 4x

Python Question

I have a dataframe below

`A B`

0 a 1

1 a 2

2 c 3

3 c 4

4 e 5

I would like to get summing result below.key = column A

`df.B.groupby(df.A).agg(np.sum)`

But I want to add specific row.

`B`

a 3

b 0

c 7

d 0

e 5

f 0

but I should add row "b" and "d"."f"

How can I get this result ?

Answer

Use `reindex`

```
df.groupby('A').B.sum().reindex(list('abcdef'), fill_value=0)
A
a 3
b 0
c 7
d 0
e 5
f 0
Name: B, dtype: int64
```

Source (Stackoverflow)

Comments