np.select代替for while循环

如何解决np.select代替for while循环

我的目标是大幅提高我的代码,尽管我不知道如何,我认为可以使用np.select来完成。

这是我的代码执行时的当前输出:

date  starting_temp  average_high  average_low  limit_temp observation_date   Date_Limit_reached
2019-12-03 22:30:00 NaN             13.0          14.8        NaN                          nan                
2019-12-03 23:00:00 NaN             14.7          14.9        NaN                          nan                
2019-12-03 23:30:00 NaN             13.0          13.9        NaN                          nan                
2019-12-04 00:00:00  13.2           13.0          14.7        NaN                          2019-12-04 10:00:00
2019-12-04 00:30:00 NaN             14.0          13.8        NaN                          nan                
2019-12-04 01:00:00 NaN             13.9          13.8        NaN                          nan                
2019-12-04 01:30:00 NaN             13.6          14.8        NaN                          nan                
2019-12-04 02:00:00 NaN             13.1          14.5        NaN                          nan                
2019-12-04 02:30:00 NaN             14.9          13.7        NaN                          nan                
2019-12-04 03:00:00 NaN             14.2          14.1        NaN                          nan                
2019-12-04 03:30:00 NaN             13.4          14.1        NaN                          nan                
2019-12-04 04:00:00 NaN             14.3          13.0        NaN                          nan                
2019-12-04 04:30:00 NaN             13.5          14.1        NaN                          nan                
2019-12-04 05:00:00 NaN             13.6          13.4        NaN                          nan                
2019-12-04 05:30:00 NaN             14.5          13.9        NaN                          nan                
2019-12-04 06:00:00 NaN             14.4          14.5        NaN                          nan                
2019-12-04 06:30:00 NaN             13.7          14.2        NaN                          nan                
2019-12-04 07:00:00 NaN             13.7          14.2        NaN                          nan                
2019-12-04 07:30:00 NaN             13.2          14.4        NaN                          nan                
2019-12-04 08:00:00 NaN             13.9          13.1        NaN                          nan                
2019-12-04 08:30:00 NaN             13.9          14.4        NaN                          nan                
2019-12-04 09:00:00 NaN             14.4          13.9        NaN                          nan                
2019-12-04 09:30:00 NaN             14.4          13.8        NaN                          nan                
2019-12-04 10:00:00 NaN             15.0          14.0        NaN                          nan                
2019-12-04 10:30:00 NaN             13.2          13.2        NaN                          nan                
2019-12-04 11:00:00 NaN             14.0          13.3        NaN                          nan                
2019-12-04 11:30:00 NaN             14.2          13.4        NaN                          nan                
2019-12-04 12:00:00 NaN             14.2          13.4        NaN                          nan                
2019-12-04 12:30:00 NaN             13.7          13.6        NaN                          nan                
2019-12-04 13:00:00 NaN             14.1          13.3        NaN                          nan                
2019-12-04 13:30:00 NaN             13.1          14.1        NaN                          nan                
2019-12-04 14:00:00 NaN             13.2          14.3        NaN                          nan                
2019-12-04 14:30:00 NaN             13.7          13.8        NaN                          nan         

产生最终df ['Date_Limit_reached']列的代码太慢了,我在下面添加了它。我想尽可能将其结构更改为np.select

    new_col = []
    
    df_size = len(df)
    
    # Loop the dataframe
    for ind in df.index:
        if not math.isnan(df['starting_temp'][ind]):   
            entry_price_val = df['starting_temp'][ind]
            count = 0
            hasValue = False
    
            while count < df_size:
       
                if df['starting_temp'][ind] > df['limit_temp'][ind] and df['limit_temp'][ind] >= df['asklow'][count] and df['date'][count] >= df['observation_date'][ind] :
                    new_col.append(df['date'][count])
                    hasValue = True
                    break  # Break the loop if matching value meets
                    count += 1
    
                elif df['starting_temp'][ind] < df['limit_temp'][ind] and df['limit_temp'][ind] <= df['average_high'][count] and df['date'][count] >= df['observation_date'][ind] :
                    new_col.append(df['date'][count])
                    hasValue = True
                    break  # Break the loop if matching value meets
                count += 1            
    
            # If matching value not meets,then append nan value to the column   
            if not hasValue:
                new_col.append(float('nan'))
        else:
            new_col.append(float('nan'))
    
 
   df['Date_Limit_reached'] = new_col

解决方法

由于缺少df导致我无法运行代码,我的建议是

  • 使用较少的标志,但使用具体的值。使代码更具可读性。 hasValue-> val

  • 如果有一个df['starting_temp'][ind] == df['limit_temp'][ind]条目,您将遇到问题,因为不会触发任何案例。也许这是慢代码的问题。

  • 您可以预先计算while循环中的第一个布尔表达式。这可以从上述观点解决问题

  • 您不使用entry_price_val

  • 为了进一步改进,请使用数据矢量化,在所有循环中都可以实现。 (由于无法测试,因此未显示在代码中)

这是我建议的代码

new_col = []
df_size = len(df)    
for ind in df.index:
    val = float('nan') # use data instead of flags
    
    if not math.isnan(df['starting_temp'][ind]):   
        count = 0
        
        if df['starting_temp'][ind] > df['limit_temp'][ind]:
            while count < df_size:
                if df['limit_temp'][ind] >= df['asklow'][count] and df['date'][count] >= df['observation_date'][ind] :
                    val=df['date'][count]
                    break  # Break the loop if matching value meets
                count += 1  
        elif df['starting_temp'][ind] < df['limit_temp'][ind]
            while count < df_size:
                if df['limit_temp'][ind] <= df['average_high'][count] and df['date'][count] >= df['observation_date'][ind] :
                    val = df['date'][count]
                    break  # Break the loop if matching value meets
                count += 1            
    new_col.append(val)
df['Date_Limit_reached'] = new_col

代码段未经测试,需要测试其正确性,并可能进一步改进(根据要求提供提示)。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-