Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 14215

How do I set values in a pandas dataframe to the minimum of a group if a condition is met

$
0
0

This is some example data:

lst = [['PF2', 'E1', -500, -127, 199971, 200164, True, True],        ['PR2', 'E1', -500, -167, 199655, 200124, True, True],       ['PF2', 'E1', -500, -167, 199645, 200124, False, True],       ['PF2', 'E1', -400, -127, 199971, 200564, True, True],        ['PR2', 'E1', -400, -167, 199155, 200324, True, True]]df = pd.DataFrame(lst, columns=["Name", "Part", "Rel_s", "Rel_e", "Abs_s", "Abs_e","Quality_Start", "Quality_End"])

I want to modify this dataframe to change the values of Abs_s to the smallest for each combination of Part and Rel_s (and the same thing for Abs_e with Part and Rel_ewith the largest value). This part works well with this code:

df['Abs_s'] = df.groupby(["Part", "Rel_s"])['Abs_s'].transform('min')df['Abs_e'] = df.groupby(["Part", "Rel_e"])['Abs_e'].transform('max')

I like this solution because it seems simple and easily understandable; however, I also want to take into account the Quality values so that I take the minimum (or maximum) value where Quality_Start (or Quality_End) is True. So in this case for E1, -500, the correct Abs_s value should be 199655 and not 199645.

Can I add these conditions? How else could I do this transformation?


Viewing all articles
Browse latest Browse all 14215

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>