- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我已经确定了一个 pandas 命令
timeseries.loc[z, x] = y
负责一次迭代中花费的大部分时间。现在我正在寻找更好的方法来加速它。循环甚至不包括 50k 个元素(生产目标是 ~250k 或更多),但已经需要 20 秒了。
这是我的代码(忽略上半部分,它只是计时助手)
def populateTimeseriesTable(df, observable, timeseries):
"""
Go through all rows of df and
put the observable into the timeseries
at correct row (symbol), column (tsMean).
"""
print "len(df.index)=", len(df.index) # show number of rows
global bf, t
bf = time.time() # set 'before' to now
t = dict([(i,0) for i in range(5)]) # fill category timing with zeros
def T(i):
"""
timing helper: Add passed time to category 'i'. Then set 'before' to now.
"""
global bf, t
t[i] = t[i] + (time.time()-bf)
bf = time.time()
for i in df.index: # this is the slow loop
bf = time.time()
sym = df["symbol"][i]
T(0)
tsMean = df["tsMean"][i]
T(1)
tsMean = tsFormatter(tsMean)
T(2)
o = df[observable][i]
T(3)
timeseries.loc[sym, tsMean] = o
T(4)
from pprint import pprint
print "times needed (total = %.1f seconds) for each command:" % sum(t.values())
pprint (t)
return timeseries
With(不重要,不慢)
def tsFormatter(ts):
"as human readable string, only up to whole seconds"
return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(ts))
..
--> 待优化代码在for循环中
(T 和 t 只是辅助函数和 dict,用于计时。)
我已经为每一步计时了。绝大多数时间:
len(df.index)= 47160
times needed (total = 20.2 seconds) for each command:
{0: 1.102,
1: 0.741,
2: 0.243,
3: 0.792,
4: 17.371}
花费在最后一步
timeseries.loc[sym, tsMean] = o
我已经下载并安装了 pypy - 但遗憾的是,它还不支持 pandas。
关于如何加快填充二维数组的任何想法?
谢谢!
编辑:抱歉,没有提到 - 'timeseries' 也是一个数据框:
timeseries = pd.DataFrame({"name": titles}, index=index)
最佳答案
更新: 从 Pandas 0.20.1 开始 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers .
============================================= ======================
@jezrael 提供了一个有趣的比较,我决定使用更多索引方法和 1000 万行 DF 重复它(实际上在这种特殊情况下大小并不重要):
设置:
In [15]: df = pd.DataFrame(np.random.rand(10**7, 5), columns=list('abcde'))
In [16]: df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10000000 entries, 0 to 9999999
Data columns (total 5 columns):
a float64
b float64
c float64
d float64
e float64
dtypes: float64(5)
memory usage: 381.5 MB
In [17]: df.shape
Out[17]: (10000000, 5)
时间:
In [37]: %timeit df.loc[random.randint(0, 10**7), 'b']
1000 loops, best of 3: 502 µs per loop
In [38]: %timeit df.iloc[random.randint(0, 10**7), 1]
1000 loops, best of 3: 394 µs per loop
In [39]: %timeit df.at[random.randint(0, 10**7), 'b']
10000 loops, best of 3: 66.8 µs per loop
In [41]: %timeit df.iat[random.randint(0, 10**7), 1]
10000 loops, best of 3: 32.9 µs per loop
In [42]: %timeit df.ix[random.randint(0, 10**7), 'b']
10000 loops, best of 3: 64.8 µs per loop
In [43]: %timeit df.ix[random.randint(0, 10**7), 1]
1000 loops, best of 3: 503 µs per loop
条形图形式的结果:
作为 DF 的时序数据:
In [88]: r
Out[88]:
method timing
0 loc 502.0
1 iloc 394.0
2 at 66.8
3 iat 32.9
4 ix_label 64.8
5 ix_integer 503.0
In [89]: r.to_dict()
Out[89]:
{'method': {0: 'loc',
1: 'iloc',
2: 'at',
3: 'iat',
4: 'ix_label',
5: 'ix_integer'},
'timing': {0: 502.0,
1: 394.0,
2: 66.799999999999997,
3: 32.899999999999999,
4: 64.799999999999997,
5: 503.0}}
绘图
ax = sns.barplot(data=r, x='method', y='timing')
ax.tick_params(labelsize=16)
[ax.annotate(str(round(p.get_height(),2)), (p.get_x() + 0.2, p.get_height() + 5)) for p in ax.patches]
ax.set_xlabel('indexing method', size=20)
ax.set_ylabel('timing (microseconds)', size=20)
关于python - pandas df.loc[z,x]=y 如何提高速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37757844/
我正在比较工作簿中的工作表。该工作簿有两张名为 PRE 和 POST 的工作表,每张工作表都有相同的 19 列。行数每天都不同,但特定一天的两张表的行数相同。该宏将 PRE 工作表中的每一行与 POS
我有一个对象数组,我一次循环遍历该数组一个对象,然后进行几次检查以查看该数组中的每个对象是否满足特定条件,如果该对象满足此条件,则复制一个属性将此对象放入数组中(该属性还包含另一个对象)。 for(v
我正在编写一个必须非常快的应用程序。我使用 Qt 5.5 和 Qt Creator,Qt 的 64 位 MSVC2013 编译版本。 我使用非常困倦的 CS 来分析我的应用程序,我看到占用最多独占时间
我有以下 CountDownTimer 在我的 Android 应用程序中不断运行。 CountDownTimer timer_status; timer_status = new CountDown
有一个优化问题,我必须调用随机森林回归器的预测函数数千次。 from sklearn.ensemble import RandomForestRegressor rfr = RandomForestR
我正在努力提高现有 Asp.Net Web 应用程序的数据访问层的性能。场景是。 它是一个基于 Web 的 Asp.Net 应用程序。 数据访问层使用 NHibernate 1.2 构建并作为 WCF
我在我的 Intel Edison 上运行 Debian,并尝试使用 ffmpeg 通过 USB 网络摄像头捕获视频。我正在使用的命令是: ffmpeg -f video4linux2 -i /dev
我有一个 For循环遍历整数 1 到 9 并简单地找到与该整数对应的最底部的条目(即 1,1,1,2,3,4,5 将找到第三个“1”条目)并插入一个空白行。我将数字与仅对应于此代码的应用程序的字符串“
我有一个带有非规范化架构(1 个表)的 postgresql 数据库,其中包含大约 400 万个条目。现在我有这个查询: SELECT count(*) AS Total, (SELECT c
在 Ltac 中实现复杂的策略时,有一些 Ltac 命令或策略调用我预计会失败以及预期失败(例如终止 repeat 或导致回溯)。这些故障通常在故障级别 0 时引发。 更高级别引发的故障“逃避”周
我正在尝试提高 ansible playbook 的性能。我有一个测试剧本如下: --- - name: Test hosts: localhost connection: local g
我正在使用 axios从 Azure 存储 Blob 下载文件 (~100MB)。 axios({ method: 'get', url: uri, onDownloadProgress:
我有一个 ClojureScript 程序,主要对集合执行数学计算。它是在惯用的、独立于主机的 Clojure 中开发的,因此很容易对其进行基准测试。令我惊讶的是(与答案对 Which is fast
我有一个程序必须在硬件允许的情况下尽快发出数千个 http 请求。在现实世界中,这些连接中的每一个都将连接到一个离散的服务器,但我已经编写了一个测试程序来帮助我模拟负载(希望如此)。 我的程序使用 A
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我正在计算 Clojure 中 3d 点云的边界框。点云表示为 Java 原始浮点数组,点云中的每个点都使用 4 个浮点存储,其中最后一个浮点未使用。像这样: [x0 y0 z0 u0 x1 y1
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引起辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the he
我正在尝试使用rayshader 包制作图像。我很高兴能够使用如下代码创建一个 png 文件: library(ggplot2) library(rayshader) example_plot <-
更新 显然,jQuery 模板可以被编译,并且它有助于显示带有 if 语句 的模板的性能 here . 但是如图here ,预编译的 jQuery 模板对我的情况没有多大作用,因为我的模板不包含逻辑
我是编程新手。我有一个启用分页的 ScrollView ,其中包含许多页面(最多十个),并且在每个页面上都有一个自定义按钮。每个自定义按钮都有一个自定义图像。我在 Interface Builder
我是一名优秀的程序员,十分优秀!