如何按比例将数组调整为一定长度?

时间:2019-05-20 09:15:53

标签: python numpy

我有一个n个长度的数组,我想将其大小调整为一定的长度以节省比例。

我想要一个这样的功能

function isStandalone () {
    return !!navigator.standalone || window.matchMedia('(display-mode: standalone)').matches;
}

// Depends on bowser but wouldn't be hard to use a
// different approach to identifying that we're running on Android
function exitsOnBack () {
    return isStandalone() && browserInfo.os.name === 'Android';
}

// Everything below has to run at page start, probably onLoad

if (exitsOnBack()) handleBackEvents();

function handleBackEvents() {
    window.history.pushState({}, '');

    window.addEventListener('popstate', () => {
        //TODO: Optionally show a "Press back again to exit" tooltip
        setTimeout(() => {
            window.history.pushState({}, '');
            //TODO: Optionally hide tooltip
        }, 2000);
    });
}

例如,输入将是一个长度为9的数组:

def rezise_my_array(array, new_lentgh)

如果将其大小调整为5,则输出为:

l = [1,2,3,4,5,6,7,8,9]

反之亦然。

由于所有要素的长度必须相同,因此我需要在pyspark上创建线​​性回归模型。

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

import numpy as np

def resize_proportional(arr, n):
    return np.interp(np.linspace(0, 1, n), np.linspace(0, 1, len(arr)), arr)

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(resize_proportional(arr, 5))
# [1. 3. 5. 7. 9.]

这里的结果是一个浮点值,但是您可以根据需要舍入或转换为整数。

答案 1 :(得分:2)

这里是使用linspace的一种方法,然后将其四舍五入以获取沿长度方向的位置,我们需要选择新元素,然后简单地索引到输入数组中即可得到所需的输出-

def resize_down(a, newlen):
    a = np.asarray(a)
    return a[np.round(np.linspace(0,len(a)-1,newlen)).astype(int)]

样品运行-

In [23]: l # larger one than given sample
Out[23]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

In [24]: resize_down(l, 2)
Out[24]: array([ 1, 11])

In [25]: resize_down(l, 3)
Out[25]: array([ 1,  6, 11])

In [26]: resize_down(l, 4)
Out[26]: array([ 1,  4,  8, 11])

In [27]: resize_down(l, 5)
Out[27]: array([ 1,  3,  6,  9, 11])

In [28]: resize_down(l, 6)
Out[28]: array([ 1,  3,  5,  7,  9, 11])

在具有900000元素的大型数组上计时,并调整为500000-

In [43]: np.random.seed(0)
    ...: l = np.random.randint(0,1000,(900000))

# @jdehesa's soln
In [44]: %timeit resize_proportional(l, 500000)
10 loops, best of 3: 22.2 ms per loop

In [45]: %timeit resize_down(l, 500000)
100 loops, best of 3: 5.58 ms per loop