sudo_woodo
sudo_woodo

Reputation: 63

Get data from a single row in pandas

Usually when I want to iterate over a csv file like this:

PRODUCTID|PRODUCTNAME|TYPE|PRODUCTDESCRIPTION
1001|Apple|Fruit|McIntosh apple
1002|Pear|Fruit|Rare name pear
1003|Potato|Root|Common potato
1004|Banana|Fruit|Banana from an island

I make this if I want to make a filter:

import pandas 
my_products = pandas.read_csv( ... )
fruits = my_products[ my_products.TYPE=="Fruit" ]

for fruit in fruits.itertuples( ):
  doSomething( fruit.PRODUCTNAME, fruit.PRODUCTDESCRIPTION )

But if I can filter just one product like this:

apple = my_products[ my_products.PRODUCTNAME="Apple" ] 

How can I get PRODUCTDESCRIPTION without needing to iterate over it as in the previous example? Because it seems I can't just make something like doSomething( "Apple", apple.PRODUCTDESCRIPTION ) or doSomething( "Apple", apple[0].PRODUCTDESCRIPTION )

Thanks in advance.

Upvotes: 0

Views: 67

Answers (1)

David Erickson
David Erickson

Reputation: 16673

Simply uses .loc to specify what you are filtering for, and then add the desired column that you want results for that row for.

my_products.loc[my_products['PRODUCTNAME'] == 'Apple']['PRODUCTDESCRIPTION']

OR

my_products.loc[my_products['PRODUCTNAME'] == 'Apple', 'PRODUCTDESCRIPTION']

Output:

0    McIntosh apple
Name: PRODUCTDESCRIPTION, dtype: object

you can then add [0] to the end to access the string. Keep in mind if there are multiple results, you could add [1], [2], etc.

my_products.loc[my_products['PRODUCTNAME'] == 'Apple']['PRODUCTDESCRIPTION'][0]

OR

my_products.loc[my_products['PRODUCTNAME'] == 'Apple', 'PRODUCTDESCRIPTION'][0]

Ouput:

'McIntosh apple'

Upvotes: 1

Related Questions