Python 根据其他列中的发生情况在pandas中创建新的时间戳

Python 根据其他列中的发生情况在pandas中创建新的时间戳,python,pandas,dataframe,timestamp,Python,Pandas,Dataframe,Timestamp,我有一个dataframe列,其中包含随机时间戳和NaT值: timestamp 01-01-2018 13:12:48 NaT NaT NaT 04-01-2018 08:15:12 NaT Nat 我想创建另一列,一旦时间戳列(col_a)中有了新的时间戳,该列将从0开始计数。我不介意该列是否是timestamp对象,但没有日期(col_B)。可能吗 timestamp col_A col_B 01-01-2018

我有一个dataframe列,其中包含随机时间戳和NaT值:

timestamp             
01-01-2018 13:12:48
NaT
NaT
NaT
04-01-2018 08:15:12
NaT
Nat
我想创建另一列,一旦时间戳列(col_a)中有了新的时间戳,该列将从0开始计数。我不介意该列是否是timestamp对象,但没有日期(col_B)。可能吗

timestamp            col_A  col_B             
01-01-2018 13:12:48  0      00:00:00
NaT                  1      00:01:00
NaT                  2      00:02:00
NaT                  3      00:03:00
04-01-2018 08:15:12  0      00:00:00
NaT                  1      00:01:00
Nat                  2      00:02:00

这是一个孤岛和缺口问题:每当
timestamp
不为空时,就会创建一个新的孤岛。你通常用某种形式的累加来解决这些问题

试试这个:

islands = df['timestamp'].notnull().cumsum()
df['col_A'] = df.groupby(islands).cumcount()
df['col_B'] = pd.to_timedelta(df['col_A'], unit='minute')

谢谢我明白了。最初,我的时间戳与索引(也包含时间戳)不一致。索引的分辨率与我用来创建col_A和col_B的timestamp列不同。我将timestamp更改回一个对象以使ist工作。