0

Current output:

df= df.loc[df['Week_Date'] == '2342',['Week_Date','Revenue']]
Week_Date Revenue
2342 7.0
2342 8.0
2342 6.0
2342 9.0
2342 9.0
2342 4.0
2342 8.0
2342 4.0

I have tried .sum() but this only returns 55. I want it in a row in the df.

df= df.loc[df['Week_Date'] == '2342',['Week_Date','Revenue']].sum()

Goal - one single row with the sum of all Revenue when Week_Date == 2342:

Week_Date Revenue
2342 55.0
Matt
  • 57
  • 5
  • Try: `df.loc[df['Week_Date'] == '2342', ['Week_Date', 'Revenue']].agg({'Week_Date': lambda x: x.iloc[0], 'Revenue': 'sum'}).to_frame().T` – Corralien Jun 06 '23 at 19:13

2 Answers2

3

You need to group on week_date, then sum

df2 = df.groupby('Week_Date')['Revenue'].sum().reset_index()

which gives:

   Week_Date   Revenue
0        2342     55.0
user19077881
  • 3,643
  • 2
  • 3
  • 14
0

Obviously, you can use groupby but you can also chain with agg:

out = (df.loc[df['Week_Date'] == '2342', ['Week_Date', 'Revenue']]
         .agg({'Week_Date': lambda x: x.iloc[0], 'Revenue': 'sum'})
         .to_frame().T)
print(out)

# Output
  Week_Date Revenue
0      2342    55.0
Corralien
  • 109,409
  • 8
  • 28
  • 52
  • Using `lambda x: x.iloc[0]` in the `agg` expression results in `ValueError: cannot perform both aggregation and transformation operations simultaneously` – user19077881 Jun 07 '23 at 20:12
  • @user19077881. `x.iloc[0]` returns a single value, `sum` also returns a single one so all operations in `agg` have to return a unique value. What are you other operations? – Corralien Jun 08 '23 at 03:57