Terry
Terry

Reputation: 1701

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?

Upvotes: 6

Views: 5070

Answers (3)

Dennis Lyubyvy
Dennis Lyubyvy

Reputation: 1120

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)

Upvotes: 2

Terry
Terry

Reputation: 2811

Add axis = 1 to your min

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

Upvotes: 5

piRSquared
piRSquared

Reputation: 294536

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

Upvotes: 5

Related Questions