Python NumPy For Your Grandma | Section 4.4 | concatenate()
- NumPy Arrays
2.1 What’s A NumPy Array
2.2 Creating NumPy Arrays
2.3 Indexing And Modifying 1-D Arrays
2.4 Indexing And Modifying Multidimensional Arrays
2.5 Basic Math
- Intermediate Array Stuff
3.4 boolean indexing
- Common Operations
4.2 Math Funcs
4.3 all and any
This video covers NumPy’s concatenate() function, used for combining two or more arrays.
import numpy as np roux = np.zeros(shape = (3, 2)) gumbo = np.ones(shape = (2,2)) # combine roux with a couple copies of itself row-wise np.concatenate((roux, roux, roux), axis = 0) # column-wise np.concatenate((roux, roux, roux), axis = 1) # combine roux and gumbo row-wise np.concatenate((roux, gumbo), axis = 0) # combine roux and gumbo column-wise np.concatenate((roux, gumbo), axis = 1) # error
You can use the concatenate() function to combine two or more arrays. This function takes two primary arguments. The first is a sequence of arrays you want to combine. This can be written as a tuple or a list. The second argument, axis, specifies the axis along which you want to combine the arrays. For example if the arrays are two dimensional, do you want to combine their rows (axis 0) or their columns (axis 1)? Numpy always uses axis 0 by default.
Let’s see an example.
Here roux is a 3x2 array and gumbo is a 2x2 array.
We can combine roux with a couple copies of itself row-wise or column-wise.
We could also combine roux and gumbo row-wise.
But, as you might expect, we’ll get an error if we try to combine them column-wise because they don’t have the same number of rows. In general, when you concatenate arrays, they must have the same exact shape excluding the axis along which you’re concatenating.