0

I have a dataframe that looks like this:

listing_id  price_4 price_5 price_6 price_7 price_8 price_9 min_price
0   42729   173.0   170.0   158.0   140.0   150.0   150.0   140.0
1   23135   184.0   180.0   173.0   150.0   160.0   160.0   150.0
2   138216  141.0   141.0   141.0   148.0   101.0   100.0   100.0
3   164989  146.0   121.0   121.0   121.0   121.0   121.0   121.0
4   301034  144.0   141.0   72.0    53.0    53.0    100.0   53.0

As you can understand, the min_price is populated by the minimum value from each row. I want to create another column that will be populated with the column name, where the value is minimum. For example, for row 0 the value should be price_7, for row 1 the value should be also price_7, and so on. If it's possible, I would love to do it without the min_price column (I have created it just for that).

Thanks!

1 Answer 1

2

Use DataFrame.filter with DataFrame.idxmin:

df['new'] = df.filter(like='price_').idxmin(axis=1)
print (df)
   listing_id  price_4  price_5  price_6  price_7  price_8  price_9  \
0       42729    173.0    170.0    158.0    140.0    150.0    150.0   
1       23135    184.0    180.0    173.0    150.0    160.0    160.0   
2      138216    141.0    141.0    141.0    148.0    101.0    100.0   
3      164989    146.0    121.0    121.0    121.0    121.0    121.0   
4      301034    144.0    141.0     72.0     53.0     53.0    100.0   

   min_price      new  
0      140.0  price_7  
1      150.0  price_7  
2      100.0  price_9  
3      121.0  price_5  
4       53.0  price_7  

Or if want all columns without first by DataFrame.iloc with slicing:

df['new'] = df.iloc[:, 1:].idxmin(axis=1)

Or if want all columns without first and last:

df['new'] = df.iloc[:, 1:-1].idxmin(axis=1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.