Python Pandas - 获取第一个符合条件的值

标签 python pandas

我们有这个功能:

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 个价格行。

示例:

GetPricePerCustomAmt(500)
Wanted Price: 281.44

GetPricePerCustomAmt(15000)
Wanted Price: 281.39

GetPricePerCustomAmt(24000)
Wanted Price: 281.08

我们该怎么做?

(如果您知道更有效的方法来获得想要的价格,请也告诉)

最佳答案

使用nextiter返回默认值,如果没有匹配的值,则返回空Series,用于过滤使用boolean indexing :

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

关于Python Pandas - 获取第一个符合条件的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52115522/

相关文章:

python - 如何处理整数值列中的非数字条目

python - 如何传递空的 pandas 查询

pandas - 在seabornfacetGrid上绘制艺术家

python - 使用 python 的文本文件标题中的条目列表

javascript - 带有 JQuery 函数的 Django 静态 Javascript 资源

python - 将 Bigquery 结果转换为 Pandas Data Frame

python - 用带反斜杠的字符串替换字符串

python - IronPython 中二维类型数组的内联初始化

Python-Imaging-Library 仅粘贴 255 alpha 的图像部分

python - 找不到代码中的语法错误?