2

I am looking for a way to find a column name with index number and value.

original = {'col1': [1, 2,0,9], 'col2': [3, 4, 2,5]}
original = pd.DataFrame(data=original)

    col1    col2
0   1        3
1   2        4
2   0        2
3   9        5

For example, I want to find where is 2 is recorded in the column. I only know index number 1 and value 2 but do not know what is column name.

I am expecting to return the only column name col1.

2 Answers 2

1

Use loc to select the row, and idxmax to select the column:

(original.loc[1] == 2).idxmax()
# 'col1'

If "1" is an integer position rather than index label, use iloc for row selection:

(original.loc[1] == 2).idxmax()
# 'col1'
Sign up to request clarification or add additional context in comments.

Comments

0

This solutions uses numpy.argwhere:

original.columns[np.argwhere(original.iloc[1,:] == 2)[0][0]]

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.