Python 熊猫:如果时间戳格式相同,则比较价格(对于循环)
我的数据框如下所示:Python 熊猫:如果时间戳格式相同,则比较价格(对于循环),python,pandas,Python,Pandas,我的数据框如下所示: time mid price 0 2019-03-13 14:45:00 0.002037 1 2019-03-13 14:49:00 0.002038 2 2019-03-13 14:50:00 0.002048 3 2019-03-13 14:51:00 0.002051 4 2019-03-14 07:49:00 0.001986 5 2019-03-14 07:50:00 0.001973 6 201
time mid price
0 2019-03-13 14:45:00 0.002037
1 2019-03-13 14:49:00 0.002038
2 2019-03-13 14:50:00 0.002048
3 2019-03-13 14:51:00 0.002051
4 2019-03-14 07:49:00 0.001986
5 2019-03-14 07:50:00 0.001973
6 2019-03-14 07:51:00 0.001973
7 2019-03-14 11:35:00 0.001972
8 2019-03-14 11:41:00 0.001968
9 2019-03-14 11:50:00 0.001970
10 2019-03-14 11:59:00 0.001972
我需要做的是比较第一个小时的价格和最后一个小时的价格。因此,在我的示例中,它将取第一个价格在2019-03-13 14:45:00
0.002037
,并将其与最后一个价格在2019-03-13 14:51:00
0.002051
进行比较,然后在我的数据框中添加一个新列,如下所示:
movement_price = price2 - price1
df_uptrend.at[index, 'price_movement'] = np.fabs(movement_price)
到目前为止,我尝试了以下内容:
for index, row in islice(df_uptrend.iterrows(), 0, 42):
if df_uptrend.loc[index, 'time'].strftime('%H') == df_uptrend.loc[index +1, 'time'].strftime('%H'):
match= True
price1 = row['mid price']
time1 = df_uptrend.loc[index, 'time']
continue
if match and df_uptrend.loc[index, 'time'].strftime('%H') !=df_uptrend.loc[index +1, 'time'].strftime('%H'):
price2 = df_uptrend.loc[index, 'mid price']
time2 = df_uptrend.loc[index, 'time']
movement_time = time2 - time1
movement_price = price2 - price1
df_uptrend.at[index, 'price_movement'] = np.fabs(movement_price)
df_uptrend.at[index, 'time_movement'] = movement_time
但它会比较一小时前的价格和一小时前的价格。。。你知道怎么解决吗?谢谢 您可以使用该功能,它可以让您按小时对数据帧重新采样。然后使用和方法提取小时和的第一个和最后一个值。然后减去这两个
像这样的事情应该可以做到:
df['price_movement'] = df.resample('60T', on='time').last() - df.resample('60T', on='time').first()
如果一小时内只有一个值,则该值将为0。您可以使用该函数,该函数允许您按小时重新采样数据帧。然后使用和方法提取小时和的第一个和最后一个值。然后减去这两个
像这样的事情应该可以做到:
df['price_movement'] = df.resample('60T', on='time').last() - df.resample('60T', on='time').first()
如果一个小时只有一个值,这将导致值为0。对于
price\u movement
列,我不确定是否理解,您希望在每小时最后一行的差异?以你的例子来说,时间是2019-03-13 14:51:00?Hi@Ben.T,是的,确实是每小时最后一次。我不确定我是否理解,对于价格变动
列,你想在哪一行以每小时最后一次计算差额?以你的例子来说,时间应该是2019-03-13 14:51:00?嗨@Ben.T,是的,是每小时最后一次。