pylearner
pylearner

Reputation: 1460

How to pick a specific value from a column based on another column with multiple ID's given

I am trying to extract a particular value from a column given the id of the row.

Data :

ID  A   B
1   cat 22
2   dog 33
3   mamal   44
4   rat 55
5   rabbit  66
6   puppy   77

Given the values of ID, I need the particular values of that column.

Example :

animal = []
id = [1,2,3] 
for i in id:
   if ID == i:
      animal.append(data.A[where ID == i])

Output:

dog

Upvotes: 0

Views: 124

Answers (2)

Fishbones78
Fishbones78

Reputation: 61

From my understanding, you are trying to retrieve a pet name from the pet ID? If so this should also work.

pet = df.A.values[df.ID==2]

This would result in pet = dog

Upvotes: 0

jezrael
jezrael

Reputation: 862691

I think you need DataFrame.loc with converting values to list:

animal = data.loc[data.ID == 2, 'A'].values.tolist()
print (animal)
['dog']

Upvotes: 2

Related Questions