- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在从 R 切换到 Python。不幸的是,我发现虽然某些结构在 R 中几乎可以立即运行,但在 Python 中它们需要几秒钟(甚至几分钟)。阅读后我发现 pandas 强烈反对使用 for 循环,建议使用矢量化和应用等其他替代方法。
在此示例代码中:从一列从最小值到最大值排序的值,保留长度为“200”的间隔后排在第一位的所有值。
import numpy as np
import pandas as pd
#Let's create the sample data. It consists of a column with random sorted values, and an extra True/False column, where we will flag the values we want
series = np.random.uniform(1,1000000,100000)
test = [True]*100000
data = pd.DataFrame({'series' : series, 'test':test })
data.sort_values(by=['series'], inplace=True)
#Loop to get rid of the next values that fall within the '200' threshold after the first next valid value
for i in data['series']:
if data.loc[data['series'] == i,'test'].item() == True:
data.loc[(data['series'] > i) & (data['series'] <= i+200 ) ,'test' ] = False
#Finally, let's keep the first values after any'200' threshold
data = data.loc[data['test']==True , 'series']
是否可以将其转换为函数、矢量化、应用或除“for”循环之外的任何其他结构以使其几乎立即运行?
最佳答案
这是我使用 while
循环的方法:
head = 0
indexes = []
while head < len(data):
thresh = data['series'].iloc[head] + 200
indexes.append(head)
head += 1
while head < len(data) and data['series'].iloc[head] < thresh:
head+=1
# output:
data = data.iloc[indexes]
# double check with your approach
set(data.loc[data['test']].index) == set(data.iloc[indexes].index)
# output: True
上述方法耗时 984 毫秒,而您的方法耗时 56 秒。
关于python - 你将如何优化这个简短但非常慢的 Python 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59740430/
void main(){ char c; unsigned char uc; unsigned short us1, us2; short s1, s2; c
我要删除 wordpress html 格式在 woocommerce 产品简短描述中。添加 电话 到处标记。我知道如何在 wp 帖子和页面中做到这一点 remove_filter( 'the_exc
我通常会打开一个命令的联机帮助页,该命令已经知道我正在搜索的选项并阅读其描述。有时只需搜索该选项即可立即生效,有时该选项在其他地方被引用,有时该选项仅作为子字符串出现在前面的文本中。 作为一个具体的例
假设我们有一个编号的圆圈。我们想从 A 点到 B 点,但不知道应该向左还是向右。你会如何使用数字来计算你应该朝哪个方向前进? 示例: 我们目前在 1。我们想继续 5。我可以直观地看到 5 更近,所以我
我正在使用以下内容将产品名称和价格添加到悬停框。 在 functions.php 中 // Alter produt loop individual products add_action( 'woo
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我有一个for循环 for ($x=1; $x<=5; $x++){ ($x == 3)? continue : true; //some code here } 现在执行时出现错误
我刚刚开始我的第一个 Java Swing 项目(之前主要做基于 Web 的应用程序),并尝试了解如何构建一个适当的架构,并在 MVC 组件之间分离关注点。 我发现的几乎所有文档都非常深入地介绍了每个
我是一名优秀的程序员,十分优秀!