I have a DataFrame that looks something like this:
Col1 Col2 Col3
0 7 11 17
1 13 12 15
2 19 23 14
3 22 19 21
I want to find the row-wise minimum after applying a function, returning the original values before the function was applied, somewhat like using the built-in min function in python with the key argument. E.g. if the function gives the absolute difference between the values of this DataFrame and a series s:
16
10
17
27
i.e. abs(Col# - s) then a new DataFrame containing the results of the function would look like:
Col1 Col2 Col3
0 9 5 1
1 3 2 5
2 2 6 3
3 5 8 6
The row-wise minimum of this would then be a series looking like:
1
2
2
5
I want a series containing the corresponding values from the original DataFrame:
17
12
19
22
I'm not aware of any minimum-finding function in pandas that has a key argument like python's built-in function.
I have found a solution that requires iterating through the rows of the DataFrame df as follows:
l = []
for idx,row in df.iterrows():
l.append(min(row,key = lambda x: abs(x-s[idx])))
pandas.Series(l)
I've also considered applying the function to the DataFrame, then finding idxmin of each row:
df1 = df.apply(lambda x: abs(x-s))
s2 = df1.idxmin(1)
which should give s2 as:
Col3
Col2
Col1
Col1
and then is there a way to select values from a DataFrame using column names from a series, i.e. using the column names from s2, return a series of values from df with the value of Col3 from the 1st row, the value of Col2 from the 2nd row, the value of Col1 from the 3rd row, and the value of Col1 from the 4th row? At the moment, the only way I know of also involves iteration:
l = []
for idx,row in df.iterrows():
l.append(row[s2[idx]])
pandas.Series(l)
Are there any better ways of achieving this besides what I've mentioned?
Dictionaries used to construct the DataFrame and Series used in the example:
data = {'Col1': [7, 13, 19, 22], 'Col2': [11, 12, 23, 19], 'Col3': [17, 15, 14, 21]}
s = {0: 16, 1: 10, 2: 17, 3: 27}