Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new column with the minimum of other columns on same row

I have the following DataFrame

Input:

A    B    C    D    E
2    3    4    5    6
1    1    2    3    2 
2    3    4    5    6

I want to add a new column that has the minimum of A, B and C for that row

Output:

A    B    C    D    E    Goal
2    3    4    5    6    2
1    1    2    3    2    1 
2    3    4    5    6    2

I have tried to use

df = df[['A','B','C]].min() 

but I get errors about hashing lists and also I think this will be the min of the whole column I only want the min of the row for those specific columns.

How can I best accomplish this?

like image 1000
Terry Avatar asked Feb 15 '19 15:02

Terry


3 Answers

Add axis = 1 to your min

df['Goal'] = df[['A','B','C']].min(axis = 1) 
like image 25
Terry Avatar answered Sep 23 '22 13:09

Terry


you have to define an axis across which you are applying the min function, which would be 1 (columns).

df['ABC_row_min'] = df[['A', 'B', 'C']].min(axis = 1)
like image 38
Dennis Lyubyvy Avatar answered Sep 23 '22 13:09

Dennis Lyubyvy


Use min along the columns with axis=1

Inline solution that produces copy that doesn't alter the original

df.assign(Goal=lambda d: d[['A', 'B', 'C']].min(1))

   A  B  C  D  E  Goal
0  2  3  4  5  6     2
1  1  1  2  3  2     1
2  2  3  4  5  6     2

Same answer put different

Add column to existing dataframe

new = df[['A', 'B', 'C']].min(axis=1)

df['Goal'] = new

df

   A  B  C  D  E  Goal
0  2  3  4  5  6     2
1  1  1  2  3  2     1
2  2  3  4  5  6     2
like image 97
piRSquared Avatar answered Sep 21 '22 13:09

piRSquared