I'm trying to manipulate my data frame similar to how you would using SQL window functions. Consider the following sample set:
import pandas as pd
df = pd.DataFrame({'fruit' : ['apple', 'apple', 'apple', 'orange', 'orange', 'orange', 'grape', 'grape', 'grape'],
'test' : [1, 2, 1, 1, 2, 1, 1, 2, 1],
'analysis' : ['full', 'full', 'partial', 'full', 'full', 'partial', 'full', 'full', 'partial'],
'first_pass' : [12.1, 7.1, 14.3, 19.1, 17.1, 23.4, 23.1, 17.2, 19.1],
'second_pass' : [20.1, 12.0, 13.1, 20.1, 18.5, 22.7, 14.1, 17.1, 19.4],
'units' : ['g', 'g', 'g', 'g', 'g', 'g', 'g', 'g', 'g'],
'order' : [2, 1, 3, 2, 1, 3, 3, 2, 1]})
+--------+------+----------+------------+-------------+-------+-------+ | fruit | test | analysis | first_pass | second_pass | order | units | +--------+------+----------+------------+-------------+-------+-------+ | apple | 1 | full | 12.1 | 20.1 | 2 | g | | apple | 2 | full | 7.1 | 12.0 | 1 | g | | apple | 1 | partial | 14.3 | 13.1 | 3 | g | | orange | 1 | full | 19.1 | 20.1 | 2 | g | | orange | 2 | full | 17.1 | 18.5 | 1 | g | | orange | 1 | partial | 23.4 | 22.7 | 3 | g | | grape | 1 | full | 23.1 | 14.1 | 3 | g | | grape | 2 | full | 17.2 | 17.1 | 2 | g | | grape | 1 | partial | 19.1 | 19.4 | 1 | g | +--------+------+----------+------------+-------------+-------+-------+
I'd like to add a few columns:
- a boolean column to indicate whether the second_pass value for that test and analysis is the highest amongst all fruit types.
- another column that lists which fruits had the highest second_pass values for each test and analysis combination.
Using this logic, I'd like to get the following table:
+--------+------+----------+------------+-------------+-------+-------+---------+---------------------+ | fruit | test | analysis | first_pass | second_pass | order | units | highest | highest_fruits | +--------+------+----------+------------+-------------+-------+-------+---------+---------------------+ | apple | 1 | full | 12.1 | 20.1 | 2 | g | true | ["apple", "orange"] | | apple | 2 | full | 7.1 | 12.0 | 1 | g | false | ["orange"] | | apple | 1 | partial | 14.3 | 13.1 | 3 | g | false | ["orange"] | | orange | 1 | full | 19.1 | 20.1 | 2 | g | true | ["apple", "orange"] | | orange | 2 | full | 17.1 | 18.5 | 1 | g | true | ["orange"] | | orange | 1 | partial | 23.4 | 22.7 | 3 | g | true | ["orange"] | | grape | 1 | full | 23.1 | 22.1 | 3 | g | false | ["orange"] | | grape | 2 | full | 17.2 | 17.1 | 2 | g | false | ["orange"] | | grape | 1 | partial | 19.1 | 19.4 | 1 | g | false | ["orange"] | +--------+------+----------+------------+-------------+-------+-------+---------+---------------------+
I'm new to pandas, so I'm sure I'm missing something very simple.
g = df.groupby(['test','analysis'])['second_pass'].agg('idxmax')will give you the indices of the rows with the maximum value forsecond_passgrouped bytestandanalysis. I don't know right now if it can detect ties though.