我给出了一个样本数据集,并且希望从原始样本数据集中选择多个样本,例如1000个样本数据块,每个数据样本由来自原始样本数据的500个数据点组成。我已经写在python这个小功能:pandas range_date减慢函数极值
import timeit
import pandas as pd
import numpy as np
sample_data = np.random.randn(10000, 15)
index = pd.date_range("20000101", periods=10000, freq='B')
sample_data_df = pd.DataFrame(sample_data, index=index)
def f(n, sample_data_df, f):
s = (1+sample_data_df).resample(f, axis=0)
r = s.prod()-1
out = r.sample(n, replace=True)
# out_index = pd.date_range(start=sample_data_df.index[0],
# periods=len(out.index),
# freq=f)
# out.index = output_index
return out
start_time = timeit.default_timer()
N = 1000
a = [f(500, sample_data_df, 'BM') for i in range(N)]
elapsed = timeit.default_timer() - start_time
print(elapsed)
如果我运行此代码需要35.8964748383秒。然而,我想有附连到每个I将取消对线路中的功能块的索引,即
def f(n, sample_data_df, f):
s = (1+sample_data_df).resample(f, axis=0)
r = s.prod()-1
out = r.sample(n, replace=True)
out_index = pd.date_range(start=sample_data_df.index[0],
periods=len(out.index),
freq=f)
out.index = output_index
return out
现在函数采用72.2418179512。疯了吧。如果需要在每个输出中都有这样的索引,我怎么能加快这一点?我知道一旦索引生成并附加到每个输出。但是,我想在其他情况下使用该函数,以便在函数内完成索引的分配时将非常感激。
此外,除了索引还有其他来源可以提高速度吗?因为即使没有索引35.8964748383也是很长时间的。
你需要在函数中重新取样? – DJK
@ djk47463是的,该函数实际上是一个类的方法,其目的是重新采样。我在想的是编写一个装饰器来添加索引。那是pythonic?你知道为什么在熊猫中编制索引太慢吗?对于像我这样的初学者来说,索引听起来像是一件相当便宜的事情。日期类型是否不能在熊猫中有效处理? – math
频率大于一天的重采样/日期范围是熊猫中已知的性能问题,请参阅相关问题,欢迎提供帮助! https://github.com/pandas-dev/pandas/issues/16463 – chrisb