# Cave of Python

»»» Numpy Functions

## Numpy Functions

Numpy has a number of functions that can be applied to Numpy arrays.

Some of these are element-wise functions that operate separately on each element of the array and return an array of the same size with the resulting values. Others are aggregate functions that return a single number calculated from apply the function to all values.

#### Element-wise Functions

Some of the most important element-wise functions are trig functions like sin, cos, etc. and mathematical functions like log, round, ceil (round upwards) and so on.

``````import numpy as np

values = np.arange(10)
print(values)
print()

values = np.sin(values)
print(values)
print()

values = np.round(values)
print(values)
print()``````
``````[0 1 2 3 4 5 6 7 8 9]

[ 0.          0.84147098  0.90929743  0.14112001 -0.7568025  -0.95892427
-0.2794155   0.6569866   0.98935825  0.41211849]

[ 0.  1.  1.  0. -1. -1. -0.  1.  1.  0.]``````

#### Aggregate Functions

Sum and average are among the most important aggregate Numpy functions. Both are implemented both as methods and as functions. var and std (variance and standard deviation) are also very useful.

``````import numpy as np

values = np.arange(10)
print(values)
print()

# Function version of sum.
print(np.sum(values))
print()

# Method version of sum
print(values.sum())
print()

# Arithmetical mean, function
print(np.average(values))
print()

# Arithmetical mean, method
print(values.mean())
print()``````
``````[0 1 2 3 4 5 6 7 8 9]

45

45

4.5

4.5``````

#### Multidimensional Arrays: Choosing an Axis

If we want to use an aggregate function like sum or average on a multidimensional array, we have to choose which axis we want to sum along.

``````import numpy as np

values = np.arange(6).reshape(2, 3)
print(values)
print()

# Default sums entire array
print(values.sum())
print()

# Sum the rows
print(values.sum(axis=0))
print()

# Sum the columns
print(values.sum(axis=1))
print()``````
``````[[0 1 2]
[3 4 5]]

15

[3 5 7]

[ 3 12]``````

Blog at WordPress.com.