# Summing dataFrame by index over rows

**URL:** <https://discourse.julialang.org/t/summing-dataframe-by-index-over-rows/93205>\
**Category:** New to Julia\
**Created:** [January 19, 2023, 10:35am UTC](https://discourse.julialang.org/t/summing-dataframe-by-index-over-rows/93205 "2023-01-19T10:35:13Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ditfurth](https://avatars.discourse-cdn.com/v4/letter/d/3e96dc/32.png) [@ditfurth](https://discourse.julialang.org/u/ditfurth)\
**Post date:** [January 19, 2023, 10:35am UTC](https://discourse.julialang.org/t/summing-dataframe-by-index-over-rows/93205/1 "2023-01-19T10:35:13Z")

</div>

Hi all,

I am trying to sum a dataframe by group ‘x1’. This works as follows:

numcols = columns to be summed  
summed\_df = combine(DataFrames.groupby(df, :x1), numcols .=\> sum .=\> numcols)

However, I am trying to make 2 adjustments and just cannot figure it out:

1. I am trying to add 1 for each sum. Thus I have tried something like this:  
summed\_df = combine(DataFrames.groupby(df, :x1), numcols .=\> x → sum(x) + 1 .=\> numcols, ungroup = true)

But this does not work? Why not? the function should still work?

1. By summing like this, the rows of the dataframe collapse. Is there any way to efficiently restore the original size of the dataframes?

Right now, I solve this by merging the collapsed version to the original version. Merge(original, collapsed, 1-to-many merge). I tried to add the option ungroup = true but it does not do anything.

Many thanks!

---

<div class="post-metadata">

**Author:** ![jules](https://avatars.discourse-cdn.com/v4/letter/j/41988e/32.png) [@jules](https://discourse.julialang.org/u/jules)\
**Post date:** [January 19, 2023, 12:00pm UTC](https://discourse.julialang.org/t/summing-dataframe-by-index-over-rows/93205/2 "2023-01-19T12:00:27Z")

</div>

To keep the rows, use `transform` instead of `combine`. To avoid the error, put parentheses around your anonymous function `(x → sum(x) + 1)`. Otherwise `.=> numcols` becomes part of the function.

---

<div class="post-metadata">

**Author:** ![ditfurth](https://avatars.discourse-cdn.com/v4/letter/d/3e96dc/32.png) [@ditfurth](https://discourse.julialang.org/u/ditfurth)\
**Post date:** [January 19, 2023, 1:40pm UTC](https://discourse.julialang.org/t/summing-dataframe-by-index-over-rows/93205/3 "2023-01-19T13:40:50Z")

</div>

Thanks a ton! That makes a lot of sense.
