PythonRunner
PythonRunner

Reputation: 161

Return column name from index and value with pandas

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.

Upvotes: 2

Views: 150

Answers (2)

Rajat Jain
Rajat Jain

Reputation: 2022

This solutions uses numpy.argwhere:

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

Upvotes: 0

cs95
cs95

Reputation: 402293

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'

Upvotes: 1

Related Questions