Python dataframe在每天满足特定条件的时间后设置为true
我需要将条件列设置为True,在价格为每天20或更高的时间之后,如下图所示 我想避免使用apply函数,因为我获得了数百万数据。我认为应用需要太多的时间。每天使用或,并通过以下方式进行比较:Python dataframe在每天满足特定条件的时间后设置为true,python,pandas,dataframe,Python,Pandas,Dataframe,我需要将条件列设置为True,在价格为每天20或更高的时间之后,如下图所示 我想避免使用apply函数,因为我获得了数百万数据。我认为应用需要太多的时间。每天使用或,并通过以下方式进行比较: 如果还需要按照compid进行测试: df['condition'] = df.groupby(['compid', df['datetime'].dt.date])['price'].cummax().ge(20) 您可以使用: 或者,如果需要条件列中的bool值,请执行以下操作: In [130
如果还需要按照
compid
进行测试:
df['condition'] = df.groupby(['compid', df['datetime'].dt.date])['price'].cummax().ge(20)
您可以使用: 或者,如果需要
条件
列中的bool
值,请执行以下操作:
In [1309]: df['condition'] = np.where(df.groupby(df.datetime.dt.date).price.cumsum().ge(20), True, False)
In [1310]: df
Out[1310]:
compid datetime price condition
0 1 2020-11-06 00:00:00 10 False
1 1 2020-11-06 00:00:10 20 True
2 1 2020-11-06 00:00:20 5 True
3 1 2020-11-07 00:00:00 20 True
4 1 2020-11-07 00:00:10 5 True
5 1 2020-11-07 00:00:20 25 True
df['condition'] = df.groupby(['compid', df['datetime'].dt.date])['price'].cummax().ge(20)
print (df)
compid datetime price condition
0 1 2020-11-06 00:00:00 10 False
1 1 2020-11-06 00:00:10 20 True
2 1 2020-11-06 00:00:20 5 True
3 1 2020-11-07 00:00:00 20 True
4 1 2020-11-07 00:00:10 5 True
5 1 2020-11-07 00:00:20 25 True
In [1306]: import numpy as np
In [1307]: df['condition'] = np.where(df.groupby(df.datetime.dt.date).price.cumsum().ge(20), 'TRUE', 'FALSE')
In [1308]: df
Out[1308]:
compid datetime price condition
0 1 2020-11-06 00:00:00 10 FALSE
1 1 2020-11-06 00:00:10 20 TRUE
2 1 2020-11-06 00:00:20 5 TRUE
3 1 2020-11-07 00:00:00 20 TRUE
4 1 2020-11-07 00:00:10 5 TRUE
5 1 2020-11-07 00:00:20 25 TRUE
In [1309]: df['condition'] = np.where(df.groupby(df.datetime.dt.date).price.cumsum().ge(20), True, False)
In [1310]: df
Out[1310]:
compid datetime price condition
0 1 2020-11-06 00:00:00 10 False
1 1 2020-11-06 00:00:10 20 True
2 1 2020-11-06 00:00:20 5 True
3 1 2020-11-07 00:00:00 20 True
4 1 2020-11-07 00:00:10 5 True
5 1 2020-11-07 00:00:20 25 True