Empty array
np.empty((2,3))
Note that in this case, the values in this array are not set. This way of creating an array is therefore only useful if the array is filled later in the code.
From a list
np.array([0,1,2,3])
# Out: array([0, 1, 2, 3])
Create a range
np.arange(4)
# Out: array(...
x = np.arange(4)
x
#Out:array([0, 1, 2, 3])
scalar addition is element wise
x+10
#Out: array([10, 11, 12, 13])
scalar multiplication is element wise
x*2
#Out: array([0, 2, 4, 6])
array addition is element wise
x+x
#Out: array([0, 2, 4, 6])
array multiplication is element wise
x...
Slice syntax is i:j:k where i is the starting index (inclusive), j is the stopping index (exclusive) and k is the step size. Like other python data structures, the first element has an index of 0:
x = np.arange(10)
x[0]
# Out: 0
x[0:4]
# Out: array([0, 1, 2, 3])
x[0:4:2]
# Out:array([0, 2...
arr = np.arange(7)
print(arr)
# Out: array([0, 1, 2, 3, 4, 5, 6])
Comparison with a scalar returns a boolean array:
arr > 4
# Out: array([False, False, False, False, False, True, True], dtype=bool)
This array can be used in indexing to select only the numbers greater than 4:
arr[arr&...
The numpy.reshape (same as numpy.ndarray.reshape) method returns an array of the same total size, but in a new shape:
print(np.arange(10).reshape((2, 5)))
# [[0 1 2 3 4]
# [5 6 7 8 9]]
It returns a new array, and doesn't operate in place:
a = np.arange(12)
a.reshape((3, 4))
print(a)
# ...
Arithmetic operations are performed elementwise on Numpy arrays. For arrays of identical shape, this means that the operation is executed between elements at corresponding indices.
# Create two arrays of the same size
a = np.arange(6).reshape(2, 3)
b = np.ones(6).reshape(2, 3)
a
# array([0, 1...
filePath = "file.csv"
data = np.genfromtxt(filePath)
Many options are supported, see official documentation for full list:
data = np.genfromtxt(filePath, dtype='float', delimiter=';', skip_header=1, usecols=(0,1,3) )
The core data structure in numpy is the ndarray (short for n-dimensional array). ndarrays are
homogeneous (i.e. they contain items of the same data-type)
contain items of fixed sizes (given by a shape, a tuple of n positive integers that specify the sizes of each dimension)
One-dimensional ar...