gpt4 book ai didi

python - 获取列数据框中最后一个等于或最接近的值

转载 作者:太空宇宙 更新时间:2023-11-03 21:17:46 27 4
gpt4 key购买 nike

我的代码有问题,我正在做一些削减。

首先,这是我的数据框列:

In [23]: df['bad_%']

0 0.025
1 0.007
2 0.006
3 0.006
4 0.006
5 0.006
6 0.007
7 0.007
8 0.007
9 0.006
10 0.006
11 0.009
12 0.009
13 0.009
14 0.008
15 0.008
16 0.008
17 0.012
18 0.012
19 0.05
20 0.05
21 0.05
22 0.05
23 0.05
24 0.05
25 0.05
26 0.05
27 0.062
28 0.062
29 0.061

5143 0.166
5144 0.166
5145 0.166
5146 0.167
5147 0.167
5148 0.167
5149 0.167
5150 0.167
5151 0.05
5152 0.167
5153 0.167
5154 0.167
5155 0.167
5156 0.051
5157 0.052
5158 0.161
5159 0.149
5160 0.168
5161 0.168
5162 0.168
5163 0.168
5164 0.168
5165 0.168
5166 0.168
5167 0.168
5168 0.049
5169 0.168
5170 0.168
5171 0.168
5172 0.168
Name: bad%, Length: 5173, dtype: float64

我使用此代码检测到该值等于或最接近 0.05(控制台上引入的值)

    error = 100                     #Margin of error
valuesA = [] #array to save data
pointCut=0 #identify cut point
for index, row in df.iterrows():
if(abs(row['bad%'] - a) <= error):
valuesA = row
error = abs(row['bad%'] - a)
#Variable "a" introduced by console, in this case is "0.05"
pointCut = index

此代码返回索引 5151 中的值 "0.05",首先看起来不错,因为索引中的 "0.05"索引“5151”是最后一个“0.05”

Out [27]: 
5151 0.05

但我的目标是获得列中的最后一个值等于或最接近“0.05”,在本例中该值对应到索引“5168”中的“0.049”,我需要获取这个值。

存在允许这样做的算法吗?有什么解决方案或建议吗?提前致谢。

最佳答案

如果至少存在一个值,则解决方案:

使用[::-1]交换后面的值并得到idxmax对于最后匹配的索引值:

a = 0.05
s = df['bad%']

b = s[[(s[::-1] <= a).idxmax()]]
print (b)
5168 0.049

或者:

b = s[(s <= a)].iloc[[-1]]
print (b)
5168 0.049
Name: bad%, dtype: float64
<小时/>

如果值不存在,解决方案也有效 - 则空 Series 产生:

a = 0.05
s = df['bad%']
m1 = (s <= a)
m2 = m1[::-1].cumsum().eq(1)

b = s[m1 & m2]
print (b)
5168 0.049
Name: bad%, dtype: float64

示例数据:

df = pd.DataFrame({'bad%': {5146: 0.16699999999999998, 5147: 0.16699999999999998, 5148: 0.16699999999999998, 5149: 0.049, 5150: 0.16699999999999998, 5151: 0.05, 5152: 0.16699999999999998, 5167: 0.168, 5168: 0.049, 5169: 0.168}})

关于python - 获取列数据框中最后一个等于或最接近的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54553957/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com