Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For each row return the Column name of the smallest value - pandas [duplicate]

I am trying to find the pandas equivalent of this question.

For each row return the column name of the largest value

I want to add a new column to the below dataframe which is the column name of the lowest value in each row.

   Multi-Use  Charging  Performer  Controls  Value for Money  All Rounder
0   1.569541  0.290916   2.396734  0.881500         3.171563     1.950175
1   0.906542  2.296172   0.162809  1.604936         0.730633     0.532835
2   0.442924  0.970764   1.264364  0.295140         2.034826     0.824529
3   0.167663  1.367973   0.877306  0.683562         1.653964     0.444136
4   0.870290  0.547844   1.703054  0.209975         2.476787     1.260371

getting min is simple: df.iloc[:, 0:6].min(axis=1)

how do I return the column name based on the min?

like image 569
vagabond Avatar asked Aug 29 '17 19:08

vagabond


People also ask

Can pandas have duplicate column names?

Pandas, however, can be tricked into allowing duplicate column names. Duplicate column names are a problem if you plan to transfer your data set to another statistical language. They're also a problem because it will cause unanticipated and sometimes difficult to debug problems in Python.

How do you find the lowest value in a column in Python?

Use idxmin() function to find the index/label of the minimum value along the index axis. 2) Get Column names of minimum value in every row : Use idxmin() function with 'axis = 1' attribute to find the index/label of the minimum value along the column axis.

How do you find the minimum value in pandas?

Pandas DataFrame min() Method The min() method returns a Series with the minimum value of each column. By specifying the column axis ( axis='columns' ), the max() method searches column-wise and returns the minimum value for each row.

How do I get the minimum of two columns in pandas?

Min value between two pandas columns You can do so by using the pandas min() function twice.


1 Answers

You can do

df['lowest_col'] = df.idxmin(axis=1)

You get

    Multi-Use   Charging    Performer   Controls    Value for Money All Rounder lowest_col
0   1.569541    0.290916    2.396734    0.881500    3.171563    1.950175    Charging
1   0.906542    2.296172    0.162809    1.604936    0.730633    0.532835    Performer
2   0.442924    0.970764    1.264364    0.295140    2.034826    0.824529    Controls
3   0.167663    1.367973    0.877306    0.683562    1.653964    0.444136    Multi-Use
4   0.870290    0.547844    1.703054    0.209975    2.476787    1.260371    Controls
like image 52
Vaishali Avatar answered Nov 27 '22 04:11

Vaishali