0

I have a NumPy array A with shape (m,n) and want to run all the elements through some function f. For a non-constant function such as for example f(x) = x or f(x) = x**2 broadcasting works perfectly fine and returns the expected result. For f(x) = 1, applying the function to my array A however just returns the scalar 1.

Is there a way to force broadcasting to keep the shape, i.e. in this case to return an array of 1s?

Ben
  • 465
  • 2
  • 6
  • 17

3 Answers3

2

F(x) = 1 is not a function you need to create a function with def or lambda and return 1. Then use np.vectorize to apply the function on your array.

>>> import numpy as np
>>> f = lambda x: 1
>>> 
>>> f = np.vectorize(f)
>>> 
>>> f(np.arange(10).reshape(2, 5))
array([[1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1]])
Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

This sounds like a job for np.ones_like, or np.full_like in the general case:

def f(x):
    result = np.full_like(x, 1)  # or np.full_like(x, 1, dtype=int) if you don't want to
                                 # inherit the dtype of x
    if result.shape == 0:
        # Return a scalar instead of a 0D array.
        return result[()]
    else:
        return result
user2357112
  • 260,549
  • 28
  • 431
  • 505
0

Use x.fill(1). Make sure to return it properly as fill doesn't return a new variable, it modifies x

Priyatham
  • 2,821
  • 1
  • 19
  • 33