Kevin
Kevin

Reputation: 163

How to get 2D nparray by applying different functions to each element in 1D nparray?

I have a length n numpy array, called data. For each element in data, I want to apply k different functions (specifically, scipy.stats.norm.pdf with k different means) and result in an n x k 2D numpy array. Is there a fast way to do this without looping through all the elements in data?

I've tried writing this with loops, but I'd like it to have better performance. Haven't been able to find any resources in documentation on how to apply multiple functions to a 1d array and expand it to a 2d nparray.

Upvotes: 0

Views: 85

Answers (2)

Paul Panzer
Paul Panzer

Reputation: 53089

scipy.stats.norm is vectorized in its parameters. You can simply do:

import numpy as np
from scipy import stats

data,means = np.ogrid[-3:3:13j,-1:1:5j]
stats.norm(loc=means).pdf(data)

Upvotes: 1

Sadrach Pierre
Sadrach Pierre

Reputation: 121

This should work, just replace data with your actual list:

from scipy.stats import norm
import numpy as np
data = [1,2,3]
new_list = list(map(norm.pdf , data))
new_array = np.array([data, new_list])
print(new_array)

Output is

[[1.         2.         3.        ]
 [0.24197072 0.05399097 0.00443185]]

Upvotes: 1

Related Questions