xSeries = pd.Series([1,200,5,13,3,301],index=['b', 's', 'h', 'd', 'e','a'])
当我给出值13时,我想在值13之前获得值200.如何编写代码?如何从系列中获取指定值前面的值
xSeries = pd.Series([1,200,5,13,3,301],index=['b', 's', 'h', 'd', 'e','a'])
当我给出值13时,我想在值13之前获得值200.如何编写代码?如何从系列中获取指定值前面的值
如果我的理解正确,那么您在查找已知值之前的值为2行。在这种情况下,已知值为13
v = 13
xSeries = pd.Series([1,200,5,13,3,301],index=['b', 's', 'h', 'd', 'e','a'])
print(xSeries)
b 1
s 200
h 5
d 13
e 3
a 301
dtype: int64
idx = xSeries[xSeries == v].index
print(idx)
Index(['d'], dtype='object')
a = xSeries.index.get_loc(idx[0])
print(a)
3
print(xSeries.iloc[[a - 2]])
s 200
dtype: int64
我知道的最快方法是下降到numpy的,让它做本地搜索:
import numpy as np
xSeries[np.argwhere(xSeries.values==v).reshape(-1)[0]-1]
,对于所有返回正确的值xSeries的唯一值v
。搜索周而复始,以前的值1将为301。 如果您搜索的值不在列表中,则这会增加IndexError
,这或多或少是合适的。
值搜索没有明确定义;如果您有多个实例的值,则此搜索无法确定您的意思。它总是会找到第一个例子。但多亏了numpy,它非常快。在你的小系列中约50μsec,比我见过的最快的纯熊猫解决方案快大约15倍。
下面是一个清理版本,它还说明了如何为第一个元素设置边界情况,以便搜索不会环绕(如果不希望它)。
def prev_value(series, v):
posn = np.argwhere(series.values==v).reshape(-1)[0]-1
if posn >= 0:
return series[posn]
return None
你会调用它的东西,如:
prev_value(xSeries, 200)
@inaMinute请考虑了投票的答案是都对您有帮助,和/或标记其中一个为“最佳答案”(通过点击答案左上角的复选标记)。 –