python中change的用法_Python Pandas,使用pct_change函数重新采样数据

在Pandas 0.18或更新版本中,您可以使用Series.resample:

def percent_change(x):

if len(x):

return (x[-1]-x[0])/x[0]

ser.resample('60T', base=30).apply(percent_change)

产生

Time

2009-01-30 09:30:00 -0.014827

2009-01-30 10:30:00 -0.000120

Freq: 60T, Name: spyo, dtype: float64

如果没有base=30,ser.resample('60T')会将系列重新采样为60分钟的间隔(分钟和秒等于0)。使用base=30时,60分钟的间隔会移动30分钟。因此,Times显示9:30和10:30而不是9:00和10:00。

第一行显示从9:30到10:30的百分比变化。第二行,从10:30到最后一次ser,10:49。

apply方法允许您使用custum函数聚合60分钟的时间间隔。在the docs的最底部,您会找到resample/apply的另一个示例。

ser.resample('60T', base=30, how=percent_change)

例如,

import numpy as np

import pandas as pd

np.random.seed(2016)

N = 100

index = ((pd.date_range('2009-01-01', periods=N//2, freq='2T'))

.union(pd.date_range('2009-01-01 4:00', periods=N//2, freq='2T')))

Data = pd.DataFrame(np.random.random((N,5)),

columns='spyo spyc spyv vxxo vxxc'.split(),

index=index)

Data['vxxv'] = np.random.randint(10, size=(N,))

def percent_change(x):

if len(x):

return (x[-1]-x[0])/x[0]

print(Data.resample('60T', base=30).apply(percent_change))

产量

spyo spyc spyv vxxo vxxc \

2008-12-31 23:30:00 -0.290145 0.116518 -0.767117 0.019722 -0.329499

2009-01-01 00:30:00 0.957057 0.113174 0.331076 -0.179291 0.397392

2009-01-01 01:30:00 0.412948 -0.366011 0.092585 0.455002 2.637628

2009-01-01 02:30:00 NaN NaN NaN NaN NaN

2009-01-01 03:30:00 0.169505 -0.901438 1.287304 8.042780 -0.189155

2009-01-01 04:30:00 40.559281 -0.510897 0.316828 0.064967 0.236498

2009-01-01 05:30:00 0.009669 -0.232149 2.055451 -0.210185 0.516835

vxxv

2008-12-31 23:30:00 7.000000

2009-01-01 00:30:00 0.000000

2009-01-01 01:30:00 -0.333333

2009-01-01 02:30:00 NaN

2009-01-01 03:30:00 2.500000

2009-01-01 04:30:00 4.000000

2009-01-01 05:30:00 -0.333333

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值