如何发现熊猫数据框索引之间的差距?

har*_*on4 5 python numpy dataframe pandas

此代码创建一个具有 10 分钟范围索引的数据框:

import pandas as pd 
import datetime as dt 

date_range = pd.date_range(end=dt.datetime(2017, 1, 6, 15, 00), periods=10, freq='10Min')

df = pd.DataFrame(index=date_range)
df['A'] = 1

print(df)
Run Code Online (Sandbox Code Playgroud)

它输出:

                     A
2017-01-06 13:30:00  1
2017-01-06 13:40:00  1
2017-01-06 13:50:00  1
2017-01-06 14:00:00  1
2017-01-06 14:10:00  1
2017-01-06 14:20:00  1
2017-01-06 14:30:00  1
2017-01-06 14:40:00  1
2017-01-06 14:50:00  1
2017-01-06 15:00:00  1
Run Code Online (Sandbox Code Playgroud)

我的问题是:

当索引之间存在间隙时,如何将以下三行中的 A 列设置为 0?

例如,如果我们删除特定行:

df = df[df.index != dt.datetime(2017, 1, 6, 14, 00)]
Run Code Online (Sandbox Code Playgroud)

它输出:

                     A
2017-01-06 13:30:00  1
2017-01-06 13:40:00  1
2017-01-06 13:50:00  1
2017-01-06 14:10:00  1
2017-01-06 14:20:00  1
2017-01-06 14:30:00  1
2017-01-06 14:40:00  1
2017-01-06 14:50:00  1
2017-01-06 15:00:00  1
Run Code Online (Sandbox Code Playgroud)

现在,在 13:50 之前缺少 10 分钟范围,因此必须将以下 3 A 行设置为 0。

所以这将是想要的结果:

                     A
2017-01-06 13:30:00  1
2017-01-06 13:40:00  1
2017-01-06 13:50:00  1
2017-01-06 14:10:00  0
2017-01-06 14:20:00  0
2017-01-06 14:30:00  0
2017-01-06 14:40:00  1
2017-01-06 14:50:00  1
2017-01-06 15:00:00  1
Run Code Online (Sandbox Code Playgroud)

有一个 python 小提琴,所以你可以试试:https : //repl.it/FaXZ/2

jez*_*ael 6

您可以使用:

#get mask where difference
mask = df.index.to_series().diff() > pd.Timedelta('00:10:00')
#get position of index where True in mask
idx = mask.idxmax()
pos = df.index.get_loc(idx)
#add values by position
df.A.iloc[pos:pos + 2] = 0
print (df)
                     A
2017-01-06 13:30:00  1
2017-01-06 13:40:00  1
2017-01-06 13:50:00  1
2017-01-06 14:10:00  0
2017-01-06 14:20:00  0
2017-01-06 14:30:00  1
2017-01-06 14:40:00  1
2017-01-06 14:50:00  1
2017-01-06 15:00:00  1
Run Code Online (Sandbox Code Playgroud)
df.A.iloc[pos:pos + 5] = 0
print (df)
                     A
2017-01-06 13:30:00  1
2017-01-06 13:40:00  1
2017-01-06 13:50:00  1
2017-01-06 14:10:00  0
2017-01-06 14:20:00  0
2017-01-06 14:30:00  0
2017-01-06 14:40:00  0
2017-01-06 14:50:00  0
2017-01-06 15:00:00  1
Run Code Online (Sandbox Code Playgroud)