I am trying to get average values for last 30 days.
That means that for row #3 it would be average of Close values between 2017-12-15 00:02:00 and 2018-01-13 00:03:00 1360.618915. So far I created helping columns called minusMonth and plusDay.
Result should be average of Close values between days minusMonth and plusDay. However right now it counts same value for each period
gData['result']=gData[(gData['Local time']>gData['minusMonth']) & (gData['Local time']<gData['plusDay'])]['Close'].mean()
Local time Close minusMonth plusDay result
0 2018-01-12 00:00:00 1323.149 2017-12-15 00:00:00 2018-01-13 00:00:00 1360.618915
1 2018-01-12 00:01:00 1322.958 2017-12-15 00:01:00 2018-01-13 00:01:00 1360.618915
2 2018-01-12 00:02:00 1322.951 2017-12-15 00:02:00 2018-01-13 00:02:00 1360.618915
3 2018-01-12 00:03:00 1322.821 2017-12-15 00:03:00 2018-01-13 00:03:00 1360.618915
4 2018-01-12 00:04:00 1322.801 2017-12-15 00:04:00 2018-01-13 00:04:00 1360.618915
... ... ... ... ... ...
1172095 2020-04-04 23:55:00 1617.048 2020-03-07 23:55:00 2020-04-05 23:55:00 1360.618915
1172096 2020-04-04 23:56:00 1617.048 2020-03-07 23:56:00 2020-04-05 23:56:00 1360.618915
1172097 2020-04-04 23:57:00 1617.048 2020-03-07 23:57:00 2020-04-05 23:57:00 1360.618915
1172098 2020-04-04 23:58:00 1617.048 2020-03-07 23:58:00 2020-04-05 23:58:00 1360.618915
1172099 2020-04-04 23:59:00 1617.048 2020-03-07 23:59:00 2020-04-05 23:59:00 1360.618915
1172100 rows × 9 columns
When I do it with text instead of column reference, it works.
[IN] gData[(gData['Local time']>'2018.05.20') & (gData['Local time']<'2018.06.20')]['Close'].mean()
[OUT]1294.6491271981902
I have been stucked on this couple days, hopefully somebody can help.
You can use lambda function to apply on the entire dataframe with axis = 1
since it should be applied to every row of the dataframe.
df['result'] = df.apply(lambda x: df[(x['Local time']>df['minusMonth']) & (x['Local time']<df['plusDay'])]['Close'].mean(), axis = 1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.