I have some data like this:
df = pd.DataFrame({'x':[1,2,3,1,1,2,3,3,2],
'y':['n', 'n', 'p', 'p', 'n', 'n', 'n', 'p', 'n'],
'z':[52,75,77,68,92,32,62,70,34]})
I'd like to first group it by x, and then check if p exists in any of the rows of each group, and add another column to the original dataframe (or to the grouped one, and then somehow flatten it back out?) that has either None if there were no p's in that group, or the smallest number corresponding to p from the z column.
So here it'd be:
x y z t
0 1 n 52 68
3 1 p 68 68
4 1 n 92 68
x y z t
1 2 n 75 None
5 2 n 32 None
8 2 n 34 None
x y z t
2 3 p 77 70
6 3 n 62 70
7 3 p 70 70
or flattened:
x y z t
0 1 n 52 68
3 1 p 68 68
4 1 n 92 68
1 2 n 75 None
5 2 n 32 None
8 2 n 34 None
2 3 p 77 70
6 3 n 62 70
7 3 p 70 70
So first we'd do
g = df.groupby('x')
But then I'm not sure how to proceed. I'm just having a hard time wrapping my head around it and running into all sorts of pandas error.