Rohan Jacob
Rohan Jacob

Reputation: 29

Getting to know which value corresponds to a particular column value

I wish to find the exact value of the index for an input defined value of key in a dataframe, below is the code I am trying to do to get it.

data_who = pd.DataFrame({'index':data['index'], 'Publisher_Key':data['Key']})

Below is my O/P dataframe:

enter image description here

If suppose I give an input say 100 as the key value, I would like to get the O/P of the index value, which is Goat, what should I do in my code??

PS: Too many labels in the data after performing label encoding, so wanted to know the value of the labels corresponds to which category.

Upvotes: 0

Views: 192

Answers (2)

Andrey Lukyanenko
Andrey Lukyanenko

Reputation: 3851

I'd suggest three ways of doing this:

  1. Using pandas:
data_who.loc[data_who['key'] == 100, 'index'].values[0]
>>> 'Goat'
  1. Using python dictionaries:
who_dict = dict(zip(data_who['key'], data_who['index']))
who_dict[100]
>>> 'Goat'
  1. Finally, if you were using LabelEncoder from skearn, it can inverse transform values:
le = LabelEncoder()
le.fit(animals) # fit on the list of animals
le.inverse_transform([100])

Upvotes: 1

dataista
dataista

Reputation: 3457

If index is a column, then you can do as follows:

data.loc[data['Key'] == 100, 'index'].iloc[0]
>>> 'Zebra'

Or other option:

data[data['Key'] == 100]['index'].iloc[0]
>>> 'Zebra'

If index is the index of the dataframe, replace ['index'] with .index.

As a side note: you shouldn't name a column index in pandas, it's a concept itself and naming a column that way could be misleading.

Upvotes: 2

Related Questions