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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With