Pandas min() of selected row and columns Pandas min() of selected row and columns python python

Pandas min() of selected row and columns


This is a one-liner, you just need to use the axis argument for min to tell it to work across the columns rather than down:

df['Minimum'] = df.loc[:, ['B0', 'B1', 'B2']].min(axis=1)

If you need to use this solution for different numbers of columns, you can use a for loop or list comprehension to construct the list of columns:

n_columns = 2cols_to_use = ['B' + str(i) for i in range(n_columns)]df['Minimum'] = df.loc[:, cols_to_use].min(axis=1)


For my tasks a universal and flexible approach is the following example:

df['Minimum'] = df[['B0', 'B1', 'B2']].apply(lambda x: min(x[0],x[1],x[2]), axis=1)

The target column 'Minimum' is assigned the result of the lambda function based on the selected DF columns['B0', 'B1', 'B2']. Access elements in a function through the function alias and his new Index(if count of elements is more then one). Be sure to specify axis=1, which indicates line-by-line calculations. This is very convenient when you need to make complex calculations. However, I assume that such a solution may be inferior in speed.

As for the selection of columns, in addition to the 'for' method, I can suggest using a filter like this:

calls_to_use = list(filter(lambda f:'B' in f, df.columns))

literally, a filter is applied to the list of DF columns through a lambda function that checks for the occurrence of the letter 'B'.

after that the first example can be written as follows:

calls_to_use = list(filter(lambda f:'B' in f, df.columns))    df['Minimum'] = df[calls_to_use].apply(lambda x: min(x), axis=1)

although after pre-selecting the columns, it would be preferable:

df['Minimum'] = df[calls_to_use].min(axis=1)