簡體   English   中英

Python Pandas根據最小索引從數據框中提取值

[英]Python Pandas extract value from dataframe based on minimum index

我有一個df:

import pandas as pd
import numpy as np

df = pd.DataFrame({"price":[1.1,66.3,11,15.2,1.1], 
                   "qty":[14,2,1,10,1],
                   "c_h":['cheese','ham','ham','cheese','ham'],
                   "qual":['good','good','bad','good','bad']})

打印時,df如下所示:

      c_h   price  qty  qual
0  cheese     1.1   14  good
1     ham    66.3    2  good
2     ham    11.0    1   bad
3  cheese    15.2   10  good
4     ham     1.1    1   bad

我正在嘗試從df返回最小索引值的price 'c_h'=='ham' and 'qual=='bad' 最小索引是滿足條件的當前索引的最低數值[0,1,2,...]

在此示例中,尋求的最小指數為2,返回價格為11.0。

注意:我主要使用pandas但也可以使用numpy

我以為會像

df[df['c_h']=='ham' and 'qual'=='bad'].min()[index]

但這不起作用。

您想要這樣的東西:

>>> df[(df.c_h == 'ham') & (df.qual == 'bad')].index.min()
2

但是,如果您不只是想要索引,可以使用索引器:

>>> df.loc[(df.c_h == 'ham') & (df.qual == 'bad'), 'price'].iloc[0]
11.0
>>> df.loc[(df.c_h == 'ham') & (df.qual == 'bad'), 'price'].iloc[[0]]
2    11.0
Name: price, dtype: float64

請注意,以上是第一個索引,而不是最低索引。 如果索引是正常的int-range索引,則它們將是等效的。

但是,如果不是這樣:

>>> df.index = [3,1,2,4,0]
>>> df
      c_h  price  qty  qual
3  cheese    1.1   14  good
1     ham   66.3    2  good
2     ham   11.0    1   bad
4  cheese   15.2   10  good
0     ham    1.1    1   bad
>>> df.loc[(df.c_h == 'ham') & (df.qual == 'bad'), 'price']
2    11.0
0     1.1
Name: price, dtype: float64

然后以相同的方式獲得一個:

>>> df.loc[(df.c_h == 'ham') & (df.qual == 'bad'), 'price'].iloc[[0]]
2    11.0
Name: price, dtype: float64

但是最低的要求具有以下效果:

>>> df.loc[(df.c_h == 'ham') & (df.qual == 'bad'), 'price'].sort_index().iloc[[0]]
0    1.1
Name: price, dtype: float64

您可以使用'pandas.DataFrame.query()'方法:

df.query("col1 == value1 and col2==value2").sort_index()["target_column"].iloc[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM