熊猫在范围之间找到idxmax()

时间:2019-01-22 09:56:13

标签: python pandas

我有这个时间序列df:

                    Current
2018-09-01 00:00      -0.01
2018-09-01 00:01      -0.03
2018-09-01 00:02      -0.01
2018-09-01 00:03       0.03
2018-09-01 00:04      -0.02
2018-09-01 00:05      -0.04
2018-09-01 00:06       0.05

我试图找到Current值大于0.01的第一个实例。如果我使用

findValue = (df['Current'] > 0.01).idxmax()

我将返回:

2018-09-01 00:03 0.03

但是,我想忽略前5行,所以返回应该是

 2018-09-01 00:06       0.05

我尝试使用shift():

findValue = (df['Current'] > 0.01).shift(5).idxmax()

但这似乎不正确...

1 个答案:

答案 0 :(得分:1)

通过索引,您可以使用iloc来使所有列都排在前面,而无需先5

N = 5
findValue = (df['Current'].iloc[N:] > 0.01).idxmax()
print (findValue)
2018-09-01 00:06

另一个想法是通过np.arange和DataFrame的长度并由&链接创建另一个布尔掩码:

m1 = df['Current'] > 0.01
m2 = np.arange(len(df)) >= 5
findValue = (m1 & m2).idxmax()
print (findValue)
2018-09-01 00:06

如果需要按DatetimeIndex中的值进行选择:

findValue = (df['Current'].loc['2018-09-01 00:05':] > 0.01).idxmax()
print (findValue)
2018-09-01 00:06:00

m1 = df['Current'] > 0.01
m2 = df.index >= '2018-09-01 00:05'
findValue = (m1 & m2).idxmax()
print (findValue)
2018-09-01 00:06:00

但是:

idxmax返回第一个False值(如果不匹配任何值):

m1 = df['Current'] > 5.01
m2 = np.arange(len(df)) >= 5
findValue = (m1 & m2).idxmax()

print (findValue)
2018-09-01 00:00:00

可能的解决方案是将nextiter一起使用:

m1 = df['Current'] > 5.01
m2 = np.arange(len(df)) >= 5
findValue = next(iter(df.index[m1 & m2]), 'no exist')

print (findValue)
no exist

如果性能很重要,请检查此不错的@jpp Q / A-Efficiently return the index of the first value satisfying condition in array

相关问题