kkjoe
kkjoe

Reputation: 795

Python dataframe get the row and column of one value

   b1  b2
0   0   1
1   2   3
2   4   5

For example, we have a dataframe a in python, is that possible to get value (b1,2) when you input 4, and get value (b2,2) when input value 5.

Also there's duplicate value in the dataframe, i want to get all their location.

Upvotes: 1

Views: 124

Answers (1)

piRSquared
piRSquared

Reputation: 294536

Option 1
one-line
Not recommended!

a.unstack().eq(4).compress(lambda x: x).index.to_series().values[0]

('b1', 2)

Option 2
np.where

i, j = np.where(a == 4)
# or faster with
# i, j = np.where(a.values == 4)
(a.columns[j[0]], a.index[i[0]])

('b1', 2)

Option 3

s = a.unstack()
pd.Series(s.index.values, s.values).loc[4]

('b1', 2)

Upvotes: 4

Related Questions