Home > Back-end >  When using group by column i just want to show two of the values in that column
When using group by column i just want to show two of the values in that column

Time:10-15

I have a data frame

df = pd.DataFrame({'Test':[0,0,1,1,2,3],
               'ROI':[12,13,14,12,13,15]})
Test ROI
0 12
0 13
1 14
1 12
2 13
3 15

And I grouped them by the column test for the average of the ROI:

Group1 = df[["Test","ROI"]].groupby("Test").mean()

It gave me:

Test ROI
0 12.5
1 13.0
2 13.0
3 15.0

But I just want the average of the ROI of the Group, 0 and 3. How can I do this? I want this:

Test ROI
0 12.5
3 15.0

CodePudding user response:

  • Use Series.isin to select only the rows where Test equals either 0 or 3, before applying df.groupby.
  • Adding as_index=False returns a df, without it, you'll get a pd.Series with Test as the index.
res = df[df.Test.isin([0,3])].groupby("Test", as_index=False).mean()

print(res)

   Test   ROI
0     0  12.5
1     3  15.0
  • Related