从熊猫的一行中获取数据

问题描述 投票:0回答:1

通常,当我要遍历这样的csv文件时:

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

如果要创建过滤器,我会这样做:

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

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

但是如果我只能过滤这样一种产品:

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

如何获得PRODUCTDESCRIPTION,而无需像前面的示例中那样对其进行迭代?因为看来我不能只做doSomething( "Apple", apple.PRODUCTDESCRIPTION )doSomething( "Apple", apple[0].PRODUCTDESCRIPTION )

提前感谢。

python pandas csv
1个回答
1
投票

仅使用.loc指定要过滤的内容,然后添加所需结果作为该行的所需列。

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

输出:

0    McIntosh apple
Name: PRODUCTDESCRIPTION, dtype: object

然后您可以在末尾添加[0]以访问字符串。请记住,如果有多个结果,则可以添加[1][2]等。>

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

输出:

'McIntosh apple'
© www.soinside.com 2019 - 2024. All rights reserved.