Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过列搜索值_Python_Pandas - Fatal编程技术网

Python 通过列搜索值

Python 通过列搜索值,python,pandas,Python,Pandas,这是我拥有的熊猫数据帧的一个示例。我需要为给定的出价找到特定的行。例如,给定bid=5,我需要返回下表中对应的行。如果我输入了一个缺少的bid,例如bid=6,那么对应于小于输入bid的最大bid的行应该返回。因此,在这种情况下,应该返回对应于bid=5的行。我如何在熊猫身上做到这一点 Bid Imp Click Spend 3 13 0.97 2 4 13 1.89 7 5 79 34.98 130 7 83 37.52 140 8 88

这是我拥有的熊猫数据帧的一个示例。我需要为给定的出价找到特定的行。例如,给定bid=5,我需要返回下表中对应的行。如果我输入了一个缺少的bid,例如bid=6,那么对应于小于输入bid的最大bid的行应该返回。因此,在这种情况下,应该返回对应于bid=5的行。我如何在熊猫身上做到这一点

Bid Imp Click   Spend
3   13  0.97    2
4   13  1.89    7
5   79  34.98   130
7   83  37.52   140
8   88  38.52   144

我认为这可以做到:

>>> df[(df['Bid']<=5)].iloc[-1,:]

Bid        5.00
Imp       79.00
Click     34.98
Spend    130.00
Name: 2, dtype: float64
试一试

如果您更喜欢单行程序,您可以将代码更改为[1],这将产生与上面相同的输出。i、 e.数据帧。移除双括号(在[2]中)会将输出更改为一个系列。一、 e

In [1]: val = 6
       df.loc[[df.loc[df.Bid <= val, 'Bid'].idxmax()]]
Out[1]: 
   Bid  Imp  Click  Spend
2    5   79  34.98    130

In [2]: df.loc[df.loc[df.Bid <= val, 'Bid'].idxmax()]
Out[2]: 
Bid        5.00
Imp       79.00
Click     34.98
Spend    130.00
Name: 2, dtype: float64
[1]中的
:val=6

df.loc[[df.loc[df.Bid这里是一个基于生成器的方法。生成器将耗尽,我们通过枚举捕获最后一项

df = df.sort_values('Bids')
df.loc[df['Bid'] == [max(enumerate(i for i in df['Bid'] if i <= 6))[1]]]

   Bid  Imp  Click  Spend
2    5   79  34.98    130
df=df.sort_值('Bids'))

df.loc[df['Bid']=[max(枚举(i代表df['Bid']中的i),如果我认为
df.iloc[np.searchsorted(df.Bid,value)]
如果任何答案解决了您的问题,您是否可以用绿色勾号将其标记为有效@dineshdileep@MabelVillalba道歉只有当出价按升序排列时,这才有效。虽然这是一个先决条件,但可以通过
df.sort_值(by='Bid',升序=True)来解决
。这仅在按升序排列投标时有效
>>> df = df.sort_values(by='Bid',ascending=True)
def get_bid(val):
    # find the index of the maximum bid below or equal val
    index = df.loc[df.Bid <= val, 'Bid'].idxmax()
    return df.loc[[index]]
In []: get_bid(6)
Out[]: 
   Bid  Imp  Click  Spend
2    5   79  34.98    130

In []: get_bid(5)
Out[]: 
   Bid  Imp  Click  Spend
2    5   79  34.98    130

In []: get_bid(4)
Out[]: 
   Bid  Imp  Click  Spend
1    4   13   1.89      7
In [1]: val = 6
       df.loc[[df.loc[df.Bid <= val, 'Bid'].idxmax()]]
Out[1]: 
   Bid  Imp  Click  Spend
2    5   79  34.98    130

In [2]: df.loc[df.loc[df.Bid <= val, 'Bid'].idxmax()]
Out[2]: 
Bid        5.00
Imp       79.00
Click     34.98
Spend    130.00
Name: 2, dtype: float64
df = df.sort_values('Bids')
df.loc[df['Bid'] == [max(enumerate(i for i in df['Bid'] if i <= 6))[1]]]

   Bid  Imp  Click  Spend
2    5   79  34.98    130
df.iloc[df[df['Bid'] <= 6].index[-1]]