What is the proper way to apply math.ceil to an entire array? See the following Python code:
index = np.zeros(len(any_array))
index2 = [random.random() for x in xrange(len(any_array))
##indexfinal=math.ceil(index2) <-?
And I want to return the ceiling value of every element within the array. Documentation states that math.ceil returns the ceiling for any input x, but what is the best method of applying this ceiling function to every element contained within the array?
Use the numpy.ceil()
function instead. The Numpy package offers vectorized versions of most of the standard math functions.
In [29]: import numpy as np
In [30]: a = np.arange(2, 3, 0.1)
In [31]: a
Out[31]: array([ 2. , 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9])
In [32]: np.ceil(a)
Out[32]: array([ 2., 3., 3., 3., 3., 3., 3., 3., 3., 3.])
This technique should work on arbitrary ndarray
objects:
In [53]: a2 = np.indices((3,3)) * 0.9
In [54]: a2
Out[54]:
array([[[ 0. , 0. , 0. ],
[ 0.9, 0.9, 0.9],
[ 1.8, 1.8, 1.8]],
[[ 0. , 0.9, 1.8],
[ 0. , 0.9, 1.8],
[ 0. , 0.9, 1.8]]])
In [55]: np.ceil(a2)
Out[55]:
array([[[ 0., 0., 0.],
[ 1., 1., 1.],
[ 2., 2., 2.]],
[[ 0., 1., 2.],
[ 0., 1., 2.],
[ 0., 1., 2.]]])
You can use map()
function in python which takes a method as first argument and an iterable as second argument and returns a iterable with the given method applied at each element.
import math
arr = [1.2, 5.6, 8.0, 9.4, 48.6, 5.3]
arr_ceil = map(math.ceil, arr)
print arr_ceil
>>> [2.0, 6.0, 8.0, 10.0, 49.0, 6.0]
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