Brandon Ginley
Brandon Ginley

Reputation: 269

Applying math.ceil to an array in python

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?

Upvotes: 5

Views: 7277

Answers (3)

Mr. Hosseini
Mr. Hosseini

Reputation: 7

you can use this method easily:

>>> array = [0, 0, 0, 3, 4, 5, 6, 7, 8, 9]
>>> np.clip(array, 1, 8)
array([1, 1, 1, 3, 4, 5, 6, 7, 8, 8])

documentation on: https://numpy.org/doc/stable/reference/generated/numpy.clip.html

or do this as same:

You can use any sample array and I use a random one. so I will put a ceiling for it elements as you asked.

sample that I'm going to filter it: [10 20 30 40 45 50 55 60 65 70 75 80]

cod snippet:

import numpy as np
Sample_array = np.array([10,20,30,40,45,50,55,60,65,70,75,80])

Result = np.where(Sample_array > 45, 0, Sample_array)
print("Resulted array: ", Result)

Resulted array: [10 20 30 40 45 0 0 0 0 0 0 0]

Upvotes: -2

holdenweb
holdenweb

Reputation: 37023

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

Upvotes: 5

ZdaR
ZdaR

Reputation: 22954

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]

Upvotes: 3

Related Questions