I'm using python and pandas to work on some data. My data looks like the following:
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar'],
'B' : [1, 2, 3, 4, 5, 6],
'C' : [True, False, True, True, False, True]})
print(df)
A B C
0 foo 1 True
1 bar 2 False
2 foo 3 True
3 bar 4 True
4 foo 5 False
5 bar 6 True
What I would like to do:
- Groupby by "A"
- Select the value B by groups where C == True
- Calculate a mean value on this selection
- Create a new column "D" to store theses values
So the result would be:
A B C D
0 foo 1 True 2
1 bar 2 False 5
2 foo 3 True 2
3 bar 4 True 5
4 foo 5 False 2
5 bar 6 True 5
I have tried some mixes of groupby, filter and transform, but I cannot succed to make it work. I imagine the solution close to the followings
df.groupby(["A"])[df.loc[df["C"] == True, "B"]].transform("mean")
or
df.groupby(["A"]).filter(lambda x: x["D"] == True)["B"].transform("mean")
But none of these syntax work.
Thanks for helping me and people in general,