当前位置: 首页 > 知识库问答 >
问题:

基于列值从Dataframe提取行

史超英
2023-03-14

我将如何从从excel文件创建的Dataframe中提取列与特定值匹配的行?

以下是Dataframe中的几行:

    Food            Men     Women
0   Total fruit     86.20   88.26
1   Apples, Total   89.01   89.66
2   Apples as fruit 89.18   90.42
3   Apple juice     88.78   88.42
4   Bananas         95.42   94.18
5   Berries         84.21   81.73
6   Grapes          88.79   88.13

这是我用来读取excel文件的代码,选择我需要的列并适当地重命名它们:

data1= pd.read_excel('USFoodCommodity.xls', sheetname='94-98 FAH', skiprows=76,skip_footer=142, parse_cols='A, H, K')
data1.columns = ['Food', 'Men', 'Women']

# Try 1: data1 = data1[data1['Food'].isin(['Total fruit']) == True] works
# Try 2: data1 = data1[data1['Food'].isin(['Apple, Total']) == True] doesn't work
# Try 3: data1 = data1.iloc[[1]] returns Apples, Total but not appropriate to use integer index
# Try 4: data1[data1['Food'] == 'Berries'] doesn't work

到目前为止,根据诸如这个、这个或这里的答案,我只能返回第一个索引,其中Food=“Total fruit”。当我尝试上述其他方法时,我只得到列名,例如:

Food    Men Women

我对熊猫不熟悉,看不出哪里出了问题。为什么我可以提取第一行食物==总水果,而不是其他任何东西?

共有3个答案

微生新翰
2023-03-14

这个问题可能很老了,但这里有一个更简单和直观的方法

注意:此解决方案仅适用于熊猫

现在可以使用. query()方法从数据框中选择列。

这很简单:

df.query('column == value') # The comparison operator can be anything.

例如,在您的情况下,您可以这样查询:

data1.query('Food == "Total Fruit"')

data1.query('Food == Berries')

要访问变量,请使用@

fruit = "berries"
data1.query('Food == @fruit')

您甚至可以使用

data1.query('condition1 == value1 & condition2 == value2')

希望有帮助。

张建树
2023-03-14

使用此代码

data1= pd.read_excel('USFoodCommodity.xls', sheetname='94-98 FAH', skiprows=76,skip_footer=142, parse_cols='A, H, K')
list_of_strings_to_match = ['Total fruit', 'Berries', 'Grape']
for index, row in data1.iterrows():
   if row['Food'] in list_of_strings_to_match:
      print row
通博实
2023-03-14

对我来说,它工作得很好,可能有一些空白的问题-通过strip删除它们:

print (data1.Food.tolist())
['Total fruit', 'Apples, Total ', 'Apples as fruit', 
'Apple juice', 'Bananas', ' Berries', 'Grapes']

data1['Food'] = data1['Food'].str.strip()

print (data1.Food.tolist())
['Total fruit', 'Apples, Total', 'Apples as fruit', 
'Apple juice', 'Bananas', 'Berries', 'Grapes']

data2 = data1[data1['Food'].isin(['Total fruit'])]
print (data2)
          Food   Men  Women
0  Total fruit  86.2  88.26

data3 = data1[data1['Food'].isin(['Apples, Total'])]
print (data3)
            Food    Men  Women
1  Apples, Total  89.01  89.66

data3 = data1[data1['Food'].isin(['Berries'])]
print (data3)
      Food    Men  Women
5  Berries  84.21  81.73
 类似资料: