Pandas在两个区域之间找到idxmax()

2024-05-14 20:12:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个时间序列:

                    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()

但这似乎不对。。。你知道吗


Tags: 实例gtdfshift时间序列currentidxmax
1条回答
网友
1楼 · 发布于 2024-05-14 20:12:24

您可以通过索引将^{}用于seelct all列,而不使用第一个5

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

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

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

如果性能很重要,请检查这个nice@jpp Q/A-Efficiently return the index of the first value satisfying condition in array。你知道吗

相关问题 更多 >

    热门问题