PythonPandas获得第一个符合条件的值

2024-04-26 22:56:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我们有这个功能:

def GetPricePerCustomAmt(CustomAmt):
    data = [{"Price":281.48,"USDamt":104.84},{"Price":281.44,"USDamt":5140.77},{"Price":281.42,"USDamt":10072.24},{"Price":281.39,"USDamt":15773.83},{"Price":281.33,"USDamt":19314.54},{"Price":281.27,"USDamt":22255.55},{"Price":281.2,"USDamt":23427.64},{"Price":281.13,"USDamt":23708.77},{"Price":281.1,"USDamt":23738.77},{"Price":281.08,"USDamt":24019.88},{"Price":281.01,"USDamt":25986.95},{"Price":281.0,"USDamt":26127.45}]
    df = pd.DataFrame(data)
    df["getfirst"] = np.where(df["USDamt"] > CustomAmt, 1, 0)
    wantedprice = "??"
    print(df)
    print()
    print("Wanted Price:",wantedprice)
    return wantedprice

使用自定义USDamt调用它,如下所示:

GetPricePerCustomAmt(500)

获取此结果:

     Price    USDamt  getfirst
0   281.48    104.84         0
1   281.44   5140.77         1
2   281.42  10072.24         1
3   281.39  15773.83         1
4   281.33  19314.54         1
5   281.27  22255.55         1
6   281.20  23427.64         1
7   281.13  23708.77         1
8   281.10  23738.77         1
9   281.08  24019.88         1
10  281.01  25986.95         1
11  281.00  26127.45         1

Wanted Price: ??

我们要返回“getfirst”列中出现的第一个1的Price行

示例:

GetPricePerCustomAmt(500)
Wanted Price: 281.44

GetPricePerCustomAmt(15000)
Wanted Price: 281.39

GetPricePerCustomAmt(24000)
Wanted Price: 281.08

我们怎么做

(如果你知道一个更有效的方法来获得想要的价格,请告诉我)


Tags: 功能dataframedfdatadefnppricepd
1条回答
网友
1楼 · 发布于 2024-04-26 22:56:48

使用nextiter作为返回默认值,如果没有匹配的值并且返回为空Series,用于筛选使用^{}

def GetPricePerCustomAmt(CustomAmt):
    data = [{"Price":281.48,"USDamt":104.84},{"Price":281.44,"USDamt":5140.77},{"Price":281.42,"USDamt":10072.24},{"Price":281.39,"USDamt":15773.83},{"Price":281.33,"USDamt":19314.54},{"Price":281.27,"USDamt":22255.55},{"Price":281.2,"USDamt":23427.64},{"Price":281.13,"USDamt":23708.77},{"Price":281.1,"USDamt":23738.77},{"Price":281.08,"USDamt":24019.88},{"Price":281.01,"USDamt":25986.95},{"Price":281.0,"USDamt":26127.45}]
    df = pd.DataFrame(data)
    return next(iter(df.loc[df["USDamt"] > CustomAmt, 'Price']), 'no matched')


print(GetPricePerCustomAmt(500))
281.44
print(GetPricePerCustomAmt(15000))
281.39
print(GetPricePerCustomAmt(24000))
281.08
print(GetPricePerCustomAmt(100000))
no matched

相关问题 更多 >