Python 如何按比例将数组调整到某个长度?

Python 如何按比例将数组调整到某个长度?,python,numpy,Python,Numpy,我有一个长度为n的数组,我想将它调整到一定的长度,以保持比例 我想要一个这样的函数: 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

我有一个长度为n的数组,我想将它调整到一定的长度,以保持比例

我想要一个这样的函数:

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.]
def rezise_my_数组(数组,新长度)
例如,输入将是长度为9的数组:

l=[1,2,3,4,5,6,7,8,9]
如果我将其重新zise为长度5,则输出为:

[1,3,5,7,9]
反之亦然


我需要这个来在pyspark上创建一个线性回归模型,因为所有功能都必须具有相同的长度。

您可以这样做:

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.]

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

这里有一种方法,使用
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

给定样本的
new_length=4
的输出必须是什么?