In python pandas, I have a dataframe which looks something like this:
JavaScript
x
10
10
1
> df
2
count
3
date
4
2021-04-03 23.0
5
2021-04-04 12.0
6
2021-04-04 10.0
7
2021-04-05 42.0
8
2021-04-06 39.0
9
10
Some of the dates are repeated, with a different count value. I would like to merge these values into one row like this:
JavaScript
1
9
1
> df
2
count
3
date
4
2021-04-03 23.0
5
2021-04-04 22.0
6
2021-04-05 42.0
7
2021-04-06 39.0
8
..
9
If it’s any help the data source is a CSV file. There is likely a way to do this in a for loop but I was wondering if this can be done with a function in pandas? Thanks.
Advertisement
Answer
You can group by the index and sum the values in this case
JavaScript
1
9
1
>>> result = df.groupby(df.index)['count'].sum()
2
>>> result
3
date
4
2021-04-03 23.0
5
2021-04-04 22.0
6
2021-04-05 42.0
7
2021-04-06 39.0
8
Name: count, dtype: float64
9