Python 查找熊猫系列或数据帧中最后一个真值的索引
我试图找到布尔级数中最后一个真值的索引。我当前的代码如下所示。有没有更快更干净的方法Python 查找熊猫系列或数据帧中最后一个真值的索引,python,pandas,Python,Pandas,我试图找到布尔级数中最后一个真值的索引。我当前的代码如下所示。有没有更快更干净的方法 import numpy as np import pandas as pd import string index = np.random.choice(list(string.ascii_lowercase), size=1000) df = pd.DataFrame(np.random.randn(1000, 2), index=index) s = pd.Series(np.random.choice
import numpy as np
import pandas as pd
import string
index = np.random.choice(list(string.ascii_lowercase), size=1000)
df = pd.DataFrame(np.random.randn(1000, 2), index=index)
s = pd.Series(np.random.choice([True, False], size=1000), index=index)
last_true_idx_s = s.index[s][-1]
last_true_idx_df = df[s].iloc[-1].name
使用:
获取第一个True。在反转系列上使用argmax:
在这里:
您可以使用与Andy Hayden相同的内容:
比较:
这些计时将非常依赖于s的大小以及True的数量(和位置)
编辑:
下一个解决方案:
print s[s==True].index[-1]
编辑1:解决方案
(s[s==True].index.tolist()[-1])
已在删除的答案中。我得到
1000个循环的计时,每个循环的最佳时间为3:638µs 1000个循环,每个循环的最佳时间为3:284µs
比较我的方法和你的方法+1@EdChum有一件事有点烦人,那就是反转会创建一个拷贝(IIUC)。。。你可以直接使用数值并使用numpy反转视图,它可能会稍微快一点(但我的可读性要差得多),本质上是O(1)。@我想现在还不清楚为什么argmax
会在这里工作,但它会更快,这通常是计数EAH,最坏情况下是O(n)和短路。但它确实看起来更神奇(不太具描述性)。idxmax不是同样的方法吗?你怎么看?为什么它们中的一些没有从熊猫身上移除?我很好奇。我认为以前的情况是np.argmax
(因此.argmax
)会落入pandas.values
numpy数组,即不返回序列。现在np.argmax
返回一个序列。由您决定,不过我想说的是,对于未来的答案:您应该将它调用的时间分开(这样更容易看到哪个调用的答案)。:)这就是说,这些计时将非常依赖于s的大小以及True的数量(和位置)。为什么最慢和最快的运行之间存在如此大的差异?这是最好的解决方案。我认为last\u valid\u index
比idxmax
更清晰。我认为这种行为并不是故意的:“如果所有元素都不是NA/null,则返回None。”False
是非null的。
In [12]: s.tail()
Out[12]:
n True
e True
k False
d False
l False
dtype: bool
print s[::-1].idxmax()
In [2]: %timeit s.index[s][-1]
The slowest run took 6.92 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 35 µs per loop
In [3]: %timeit s[::-1].argmax()
The slowest run took 6.67 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 126 µs per loop
In [4]: %timeit s[::-1].idxmax()
The slowest run took 6.55 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 127 µs per loop
In [5]: %timeit s[s==True].last_valid_index()
The slowest run took 8.10 times longer than the fastest. This could mean that an intermediate result is being cached
1000 loops, best of 3: 261 µs per loop
In [6]: %timeit (s[s==True].index.tolist()[-1])
The slowest run took 6.11 times longer than the fastest. This could mean that an intermediate result is being cached
1000 loops, best of 3: 239 µs per loop
In [7]: %timeit (s[s==True].index[-1])
The slowest run took 5.75 times longer than the fastest. This could mean that an intermediate result is being cached
1000 loops, best of 3: 227 µs per loop
print s[s==True].index[-1]
(s[s==True].index.tolist()[-1])