如何根据熊猫中的某些条件保存上一行索引



我正试图找出如何根据某些条件保存前一行索引/日期。

这个操作的速度是至关重要的,所以我尝试使用矢量化操作,但到目前为止没有成功。

例如,我有这样的数据帧:

dates = pd.date_range('1/1/2000', periods=10)
data = {'date': dates}
df = pd.DataFrame.from_dict(data)
df['condition'] = [False, False, True, True, False, True, False, False, True, False]
df['desired_result'] = [np.nan, np.nan,np.nan, df.iloc[2]['date'], np.nan, df.iloc[3]['date'], np.nan, np.nan, df.iloc[5]['date'], np.nan]
date              condition    desired_result 
[0: 2000-01-01 00:00:00 False          NaT], 
[1: 2000-01-02 00:00:00 False          NaT],
[2: 2000-01-03 00:00:00 True           NaT], 
[3: 2000-01-04 00:00:00 True           2000-01-03 00:00:00], 
[4: 2000-01-05 00:00:00 False          NaT], 
[5: 2000-01-06 00:00:00 True           2000-01-04 00:00:00],
[6: 2000-01-07 00:00:00 False          NaT,
[7: 2000-01-08 00:00:00 False          NaT,
[8: 2000-01-09 00:00:00 True           2000-01-06 00:00:00],
[9: 2000-01-10 00:00:00 False          NaT],

我有个问题"节省";前一个有效行,由于缺乏知识。我怎样才能做到这一点?

以下内容应该有效:

dates = pd.date_range('1/1/2000', periods=10)
data = {'date': dates}
df = pd.DataFrame.from_dict(data)
df['condition'] = [False, False, True, True, False, True, False, False, True, False]
df['desired_result']=pd.NaT
df2=df[df['condition']==True]
df3=df[df['condition']!=True]
df2.desired_result=df2.date.shift(1)
result=pd.concat([df2,df3]).sort_index()
print(result)

最新更新