栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

将数组a中大于30的值替换为30,小于10的值替换为10。

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将数组a中大于30的值替换为30,小于10的值替换为10。

  • a = np.random.uniform(1, 50, 20)
  • 话不多说,直接上代码:

  • import numpy as np
    
    np.set_printoptions(precision=2)
    np.random.seed(100)
    a = np.random.uniform(1, 50, 20)
    print(a)
    # [27.63 14.64 21.8  42.39  1.23  6.96 33.87 41.47  7.7  29.18 44.67 11.25
    #  10.08  6.31 11.77 48.95 40.77  9.43 41.   14.43]
    
    # 方法1
    b = np.clip(a, a_min=10, a_max=30)
    print(b)
    # [27.63 14.64 21.8  30.   10.   10.   30.   30.   10.   29.18 30.   11.25
    #  10.08 10.   11.77 30.   30.   10.   30.   14.43]
    
    # 方法2
    b = np.where(a < 10, 10, a)
    b = np.where(b > 30, 30, b)
    print(b)
    # [27.63 14.64 21.8  30.   10.   10.   30.   30.   10.   29.18 30.   11.25
    #  10.08 10.   11.77 30.   30.   10.   30.   14.43]
  •  np.clip (a,a_min,a_max)

  • numpy.clip(a, a_min, a_max, out=None, **kwargs): 剪裁(限制)数组中的值。

  • 给定一个间隔,间隔之外的值将被剪裁到间隔边。例如,如果指定了[0,1]的间隔,则小于0的值变为0,大于1的值变为1。

  • np.where(condition,x,y)
  • np.where(condition,x,y) 当where内有三个参数时,第一个参数表示条件,当条件成立时where方法返回x,当条件不成立时where返回y。

  • np.where(condition) 当where内只有一个参数时,那个参数表示条件,当条件成立时,where返回的是每个符合condition条件元素的坐标,返回的是以元组的形式。
     

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/874880.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号