- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个数据框和如下所示的大函数,我想将norm_group函数应用于数据框列,但它使用apply命令花费了太多时间。有什么办法可以减少这段代码的时间吗?目前每个循环需要 24.4 秒。
import pandas as pd
import numpy as np
np.random.seed(1234)
n = 1500000
df = pd.DataFrame()
df['group'] = np.random.randint(1700, size=n)
df['ID'] = np.random.randint(5, size=n)
df['s_count'] = np.random.randint(5, size=n)
df['p_count'] = np.random.randint(5, size=n)
df['d_count'] = np.random.randint(5, size=n)
df['Total'] = np.random.randint(400, size=n)
df['Normalized_total'] = df.groupby('group')['Total'].apply(lambda x: (x-x.min())/(x.max()- x.min()))
df['Normalized_total'] = df['Normalized_total'].apply(lambda x:round(x,2))
def norm_group(a,b,c,d,e):
if a >= 0.7 and b >=1000 and c >2:
return "Both High "
elif a >= 0.7 and b >=1000 and c < 2:
return "High and C Low"
elif a >= 0.4 and b >=500 and d > 2:
return "Medium and D High"
elif a >= 0.4 and b >=500 and d < 2:
return "Medium and D Low"
elif a >= 0.4 and b >=500 and e > 2:
return "Medium and E High"
elif a >= 0.4 and b >=500 and e < 2:
return "Medium and E Low"
else:
return "Low"
%timeit df['Categery'] = df.apply(lambda x:norm_group(a=x['Normalized_total'],b=x['group']), axis=1)
每次循环 24.4 秒 ± 551 毫秒(7 次运行的平均值 ± 标准差,每次 1 次循环)
我的原始数据框中有多个文本列,并且想要应用类似的函数,与此相比,该函数需要更多的时间。
谢谢
最佳答案
您可以使用np.select
进行矢量化:
df['Category'] = np.select((df['Normalized_total'].ge(0.7) & df['group'].ge(1000),
df['Normalized_total'].ge(0.4) & df['group'].ge(500)),
('High', 'Medium'), default='Low'
)
性能:
255 ms ± 2.71 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
关于python - pandas apply function rowwise 花费太长时间下面的代码有其他选择吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58824407/
在我们的服务出现一些预期的增长之后,突然间一些更新花费了非常长的时间,这些过去非常快,直到表达到大约 2MM 记录,现在它们每个需要大约 40-60 秒。 update table1 set fiel
我在服务中实现了一个传感器事件监听器,只要采样周期和最大报告延迟低于 1 秒,该监听器就可以正常工作,但一旦我将采样周期增加到超过 1 秒,传感器就根本不会更新。 我希望采样周期为 10 秒(可能是
我使用 Tkinter GUI 来启动测量和分析过程,基本上只需单击一个按钮即可开始。由于这些测量可能需要一段时间,我尝试添加一个进度条,即这个: http://tkinter.unpythonic.
我正在尝试使用套接字发送数据包,但出现错误。 invalid conversion from ‘omnetpp::cPacket*’ to ‘inet::Packet*’ [-fpermissive]
我刚刚发现 String#split 有以下奇怪的行为: "a\tb c\nd".split => ["a", "b", "c", "d"] "a\tb c\nd".split(' ') => ["a
您好,我正在尝试 ClojureScript,我正在使用 Klipse作为我的 REPL 差不多。这可能不是它的预期用途,但因为我没有做任何太复杂的事情,所以现在没问题。 我遇到的一个问题是尝试设置计
根据下面的数据,ClockKit 会生成一次 future 的 CLKComplicationTimelineEntry 项,但对于过去的时间点,会进行 24 次调用!这是为什么? 更多详情: 我注意
我有一个 MySQL 表,这个表有一个名为 datetime_utc 的 DATETIME 列。如您所料,它是 UTC 日期和时间。在我的 Bookshelf 模型中,我定义了一个虚拟 getter,
大家好,我是二哥呀! 昨天,一位球友问我能不能给他解释一下 @SpringBootApplication 注解是什么意思,还有 Spring Boot 的运行原理,于是我就带着他扒拉了一下这个注解的源
我是一名优秀的程序员,十分优秀!