0

I have a dataframe (small sample shown below, it has more columns), and I want to find the column names with the minimum values.

enter image description here

Right now, I have the following code to deal with it:

finaldf['min_pillar_score'] = finaldf.iloc[:, 2:9].idxmin(axis="columns")

This works fine, but does not return multiple values of column names in case there is more than one instance of minimum values. How can I change this to return multiple column names in case there is more than one instance of the minimum value?

Please note, I want row wise results, i.e. minimum column names for each row.

Thanks!

3
  • please do not post images of data, provide the data as text Commented Dec 4, 2021 at 9:58
  • I cant preserve the formatting as text Commented Dec 4, 2021 at 10:01
  • wrap the data in triple backticks, I'll edit your post if needed Commented Dec 4, 2021 at 10:02

2 Answers 2

2

try the code below and see if it's in the output format you'd anticipated. it produces the intended result at least.

result will be stored in mins.

mins = df.idxmin(axis="columns")

for i, r in df.iterrows():
    mins[i] = list(r[r == r[mins[i]]].index)

Get column name where value is something in pandas dataframe might be helpful also.

EDIT: adding an image of the output and the full code context.enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

thanks so much! this was so helpful, you're a legend!
1

Assuming this input as df:

   A  B  C  D
0  5  8  9  5
1  0  0  1  7
2  6  9  2  4
3  5  2  4  2
4  4  7  7  9

You can use the underlying numpy array to get the min value, then compare the values to the min and get the columns that have a match:

s = df.eq(df.to_numpy().min()).any()
list(s[s].index)

output: ['A', 'B']

3 Comments

Hi, I wanted row wise results, i.e. minimum column names per row.
I have edited the question to include this
@Ray92 please update your question with the data as text, and please provide the expected output for clarity

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.