python - 将 Numpy 数组缩放到一定范围

标签 python arrays numpy

类似于this question ,我想将 Numpy 数组放入某个范围内,但是与链接的问题不同,我不想对其进行规范化。我怎样才能有效地做到这一点? Numpy 中是否有内置方法?

用一个例子来说明,my_scale 是我正在寻找的函数,out_range 定义了输出范围:

res = my_scale(np.array([-3, -2, -1], dtype=np.float), out_range)
assert res == [-1, 0, 1]
assert res != [-1, -2/3, -1/3]

最佳答案

asking on CodeReview 之后, 我被告知有一个内置的 np.interp完成这个:

np.interp(a, (a.min(), a.max()), (-1, +1))

为了后代,我在下面留下了我的旧答案。


我根据 this answer 中的 D3.js 代码制作了自己的函数:

import numpy as np

def d3_scale(dat, out_range=(-1, 1)):
    domain = [np.min(dat, axis=0), np.max(dat, axis=0)]

    def interp(x):
        return out_range[0] * (1.0 - x) + out_range[1] * x

    def uninterp(x):
        b = 0
        if (domain[1] - domain[0]) != 0:
            b = domain[1] - domain[0]
        else:
            b =  1.0 / domain[1]
        return (x - domain[0]) / b

    return interp(uninterp(dat))

print(d3_scale(np.array([-2, 0, 2], dtype=np.float)))
print(d3_scale(np.array([-3, -2, -1], dtype=np.float)))

关于python - 将 Numpy 数组缩放到一定范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36000843/

相关文章:

arrays - 多维数组上的 Matlab 求和性能

python - 加速 Python 中图像距离变换的计算

python - 从 Django 单元测试中获取通过或失败的输出

python - 在 ubuntu 16.04 中安装 pyodbc 和 pymssql 时遇到障碍

python - 带有 Gunicorn Dockerized 的 Flask 应用程序,监听 : http://0. 0.0.0 :8000, 但 URL 没有响应

javascript - 检查 arraylist 属性是否对所有对象都为 true

php - 在订单数组中查找重复值并替换

python - numpy ndarray 到 Pandas 数据框

python - 将 Pandas 数据框列转换为 np.datetime64

python - 在没有其他低级库的情况下使用 Python 监视文件系统事件