'How to add rows with conditions together [duplicate]
raw_data = {'id': [1,1,1,2,2,2,3,3,3],'v': [2,3,4,3,2,4,6,5,4]}
df = pd.DataFrame(raw_data, columns = ['id','v'])
I want to add "v" together if the "id" is the same. It should look like that:
id v
1 9
2 9
3 15
I tried something like:
for i in range(1, max(df_tracks["id"])+1):
if df_tracks["id"] == i:
pass
But it looks pretty wrong.
Solution 1:[1]
You can use groupby to achieve this:
In [5]: df.groupby("id", as_index=False).sum()
Out[5]:
id v
0 1 9
1 2 9
2 3 15
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rachwa |
