当大于x时,替换数组中的值

时间:2016-04-25 13:46:37

标签: python arrays numpy

我对一个简单的想法有点问题。我有一个数据数组,如果值大于X,我想替换每个值。

为了解决这个问题,我写了一个小脚本作为例子给出了同样的想法:

package xyz.cloorc.boot.mybatis;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
public class SimpleTest {

    private DataSource dsA;
    private DataSource dsB;

    @Bean(name = "dataSourceA")
    public DataSource getDataSourceA() {
        return dsA != null ? dsA : (dsA = new BasicDataSource());
    }

    @Bean(name = "dataSourceB")
    public DataSource getDataSourceB() {
        return dsB != null ? dsB : (dsB = new BasicDataSource());
    }

    @Bean(name = "sqlSessionFactoryA")
    public SqlSessionFactory getSqlSessionFactoryA() throws Exception {
        // set DataSource to dsA
        return new SqlSessionFactoryBean().getObject();
    }

    @Bean(name = "sqlSessionFactoryB")
    public SqlSessionFactory getSqlSessionFactoryB() throws Exception {
        // set DataSource to dsB
        return new SqlSessionFactoryBean().getObject();
    }
}

@Repository
public class SimpleDao extends SqlSessionDaoSupport {

    @Resource(name = "sqlSessionFactoryA")
    SqlSessionFactory factory;

    @PostConstruct
    public void init() {
        setSqlSessionFactory(factory);
    }

    @Override
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }

    public <T> T get (Object id) {
        return super.getSqlSession().selectOne("sql statement", "sql parameters");
    }
}

我想获得:

import numpy as np

# Array creation

array = np.array([0.5, 0.6, 0.9825])

print array

# If value > 0.7 replace by 0.

new_array = array[array > 0.7] == 0

print new_array

如果你能帮助我,谢谢你;)

编辑:

我没有找到这个主题如何帮助我:Replace all elements of Python NumPy Array that are greater than some value @ColonelBeauvel给出的答案在前一篇文章中没有被注意到。

2 个答案:

答案 0 :(得分:5)

我想知道为什么在@DonkeyKong提供的链接中没有提供此解决方案:

np.where(arr>0.7, 0, arr)
#Out[282]: array([ 0.5,  0.6,  0. ])

答案 1 :(得分:0)

怎么样

a = [0.5, 0.6, 0.9825]
b = [(lambda i: 0 if i > 0.7 else i)(i) for i in a]

此处lambda expressionlist comprehensions。 检查链接