How to resize array to a certain length proportionally?

al2*_*al2 5 python numpy

I have an array of n length and I want to resize it to a certain length conserving the proportions.

I would like a function like this:

def rezise_my_array(array, new_lentgh)
Run Code Online (Sandbox Code Playgroud)

For example, the input would be an array of length 9:

l = [1,2,3,4,5,6,7,8,9]
Run Code Online (Sandbox Code Playgroud)

If I rezise it to length 5, the output would be:

[1,3,5,7,9]
Run Code Online (Sandbox Code Playgroud)

or vice versa.

I need this to create a linear regression model on pyspark, since all the features must have the same length.

jde*_*esa 3

你可以这样做:

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.]
Run Code Online (Sandbox Code Playgroud)

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