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.isinto select only the rows whereTestequals either0or3, before applyingdf.groupby. - Adding
as_index=Falsereturns adf, without it, you'll get apd.SerieswithTestas 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
