我尝试了不同的选项,但我总是返回到.get_loc函数。我得到了一个大数据框架,需要找到值nearest或backfill的行索引。df看起来如下所示:
Date Product Price
0 1/1 NEG 3
1 1/1 NEG 3.3
2 1/1 NEG 5.1
3 1/1 POS 1.4
4 1/1 POS 3.7
5 1/1 POS 3.9
6 1/1 POS 4.6
7 1/2 NEG 1.2
8 ... ... ...df.columns.get_loc('Price')给我列'Price‘的索引2,但是我需要一个特殊的逐行索引('Date’和'Product'),例如:
df.loc[(df)['Date']=='1/1' & (df['Product']=='NEG')]
现在,搜索Price == 3.4:
pd.Index(df.Price).get_loc(3.4, 'nearest')
这将给我index=1,但它不能工作,因为数据太大,有多个'3.4‘。
是否有任何方法可以在某些条件下搜索最近的值,如上面所述?
发布于 2019-02-22 09:41:53
欢迎来到斯塔克溢流!
我不喜欢使用.get_loc(),所以这里有一个替代方法来获得您想要的东西。
import pandas as pd
num = 3.4
# New dataframe fit_criteria for conditions (df['Date']=='1/1') & (df['Product']=='NEG')
fit_criteria = df.loc[(df['Date']=='1/1') & (df['Product']=='NEG')]
# Find absolute difference between values in price column and num. Find the index of
# the smallest difference using .idxmin()
nearest_to_num = (fit_criteria['Price']-num).abs().idxmin()
# Final result is the index of nearest number to num
nearest_to_num如果注释不够,下面将对所发生的事情做一个更详细的解释:
Date = 1/1和Product = Neg作为条件在.loc[]中传递,我们创建了一个符合.loc[]和Product = Neg标准的数据。
fit_criteria =df.loc[(df‘’Date‘=’1/1‘)&(df’积‘=’NEG‘)]num与列price中的值之间绝对差异的数据。最后,使用.idxmin()方法返回第一个最小值的索引。
nearest_to_num =(fit_criteria‘’Price‘-num).abs().idxmin()nearest_to_num有一个1值,对应于您想要的行的索引。请注意,此方法不考虑与num相同的多个值。我希望这能充分回答你的问题,但如果你需要更多的细节或澄清,请随时通知我。
参考资料:How do I find the closest values in a Pandas series to an input number?
https://stackoverflow.com/questions/54817993
复制相似问题