Share on:

Python NumPy For Your Grandma | Section 4.4 | concatenate()
December 29, 2019

Table Of Contents

  1. Introduction
  2. 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
  3. Intermediate Array Stuff
    3.1 Broadcasting
    3.2 newaxis
    3.3 reshape
    3.4 boolean indexing
    3.5 nan
    3.6 infinity
    3.7 random
  4. Common Operations
    4.1 where
    4.2 Math Funcs
    4.3 all and any
    4.4 concatenate
    4.5 Stacking
    4.6 Sorting
    4.7 unique
  5. Challenges

This video covers NumPy’s concatenate() function, used for combining two or more arrays.

Code

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

Transcript

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.


Enjoyed this article? Show your support and buy some GormAnalysis merch.
comments powered by Disqus