Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize array to a certain length proportionally?

Tags:

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)

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

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

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

[1,3,5,7,9]

or vice versa.

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

like image 311
al2 Avatar asked May 20 '19 09:05

al2


People also ask

How do you resize an array in C++?

Once an array has been allocated, there is no built-in mechanism for resizing it in the C++ programming language. Therefore, we can avoid this problem by dynamically generating a new array, copying over the contents, and then deleting the old array.

How do I resize an array in Numpy?

NumPy: resize() functionThe resize() function is used to create a new array with the specified shape. If the new array is larger than the original array, then the new array is filled with repeated copies of a. Array to be resized.

What is resize in array?

Description. This method increases or reduces the size of the array. If the resized array will be smaller than the original array, all items within the array with indices greater than the new maximum will be lost.


1 Answers

You can do something like this:

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

The result here is a floating point value but you can round or cast to integer if you need.

like image 176
jdehesa Avatar answered Oct 06 '22 01:10

jdehesa