Week 17

NumPy

Welcome to NumPy!

NumPy (Numerical Python) is an open source Python library that is used in almost every field of science and engineering. It’s the universal standard for working with numerical data in Python, and it’s at the core of the scientific Python and PyData ecosystems. NumPy users include everyone from beginning coders to experienced researchers doing state-of-the-art scientific and industrial research and development. The NumPy API is used extensively in Pandas, SciPy, Matplotlib, scikit-learn, scikit-image and most other data science and scientific Python packages.

The NumPy library contains multidimensional array and matrix data structures (you’ll find more information about this in later sections). It provides ndarray, a homogeneous n-dimensional array object, with methods to efficiently operate on it. NumPy can be used to perform a wide variety of mathematical operations on arrays. It adds powerful data structures to Python that guarantee efficient calculations with arrays and matrices and it supplies an enormous library of high-level mathematical functions that operate on these arrays and matrices.

Installing NumPy

If you already have Python installed, you can install NumPy with:

conda install numpy

or

pip install numpy

How to import NumPy

Any time you want to use a package or library in your code, you first need to make it accessible.

In order to start using NumPy and all of the functions available in NumPy, you’ll need to import it. This can be easily done with this import statement:

import numpy as np

(We shorten numpy to np in order to save time and also to keep code standardized so that anyone working with your code can easily understand and run it.)

What is an array?

An array is a central data structure of the NumPy library. An array is a grid of values and it contains information about the raw data, how to locate an element, and how to interpret an element. It has a grid of elements that can be indexed in various ways. The elements are all of the same type, referred to as the array dtype.

An array can be indexed by a tuple of nonnegative integers, by booleans, by another array, or by integers. The rank of the array is the number of dimensions. The shape of the array is a tuple of integers giving the size of the array along each dimension.

One way we can initialize NumPy arrays is from Python lists, using nested lists for two- or higher-dimensional data.

For example:

>>> a = np.array([1, 2, 3, 4, 5, 6])

or:

>>> b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

We can access the elements in the array using square brackets like you are used to from lists. When you’re accessing elements, remember that indexing in NumPy starts at 0. That means that if you want to access the first element in your array, you’ll be accessing element “0”.

>>> print(a[0])
[1]
>>> print(b[0])
[1, 2, 3, 4]

What’s the difference between a Python list and a NumPy array

You might have noticed quite some similarities between Python lists and NumPy arrays. But what is the difference between them exactly, and why would we use arrays?

NumPy gives you an enormous range of fast and efficient ways of creating arrays and manipulating numerical data inside them. While a Python list can contain different data types within a single list, all of the elements in a NumPy array should be homogeneous. The mathematical operations that are meant to be performed on arrays would be extremely inefficient if the arrays weren’t homogeneous.

Why use NumPy?

NumPy arrays are faster and more compact than Python lists. An array consumes less memory and is convenient to use. NumPy uses much less memory to store data and it provides a mechanism of specifying the data types. This allows the code to be optimized even further.

Example: Time comparison between Numpy array and Python lists

# importing required packages
import numpy
import time

# size of arrays and lists
size = 1000000

# declaring lists
list1 = range(size)
list2 = range(size)

# declaring arrays
array1 = numpy.arange(size)
array2 = numpy.arange(size)

# capturing time before the multiplication of Python lists
initialTime = time.time()

# multiplying elements of both the lists and stored in another list
resultantList = [(a * b) for a, b in zip(list1, list2)]

# calculating execution time
print("Time taken by Lists to perform multiplication:",
	(time.time() - initialTime),
	"seconds")

# capturing time before the multiplication of Numpy arrays
initialTime = time.time()

# multiplying elements of both the Numpy arrays and stored in another Numpy array
resultantArray = array1 * array2

# calculating execution time
print("Time taken by NumPy Arrays to perform multiplication:",
	(time.time() - initialTime),
	"seconds")

What is a vector and matrix?

The NumPy ndarray class is used to represent both matrices and vectors. A vector is an array with a single dimension (there's no difference between row and column vectors), while a matrix refers to an array with two dimensions. For 3-D or higher dimensional arrays, the term tensor is also commonly used.

How to create a basic array?

This section covers np.array(), np.zeros(), np.ones(), np.empty(), np.arange(), np.linspace(), dtype

To create a NumPy array, you can use the function np.array().

All you need to do to create a simple array is pass a list to it. If you choose to, you can also specify the type of data in your list. You can find more information about data types here.

>>> import numpy as np
>>> a = np.array([1, 2, 3])

You can visualize your array this way:

Be aware that these visualizations are meant to simplify ideas and give you a basic understanding of NumPy concepts and mechanics. Arrays and array operations are much more complicated than are captured here!

Besides creating an array from a sequence of elements, you can easily create an array filled with 0’s:

>>> np.zeros(2)
array([0., 0.])

Or an array filled with 1’s:

>>> np.ones(2)
array([1., 1.])

Or even an empty array! The function empty creates an array whose initial content is random and depends on the state of the memory. The reason to use empty over zeros (or something similar) is speed - just make sure to fill every element afterwards!

>>> # Create an empty array with 2 elements
>>> np.empty(2)
array([ 3.14, 42.  ])  # may vary

You can create an array with a range of elements:

>>> np.arange(4)
array([0, 1, 2, 3])

And even an array that contains a range of evenly spaced intervals. To do this, you will specify the first number, last number, and the step size.

>>> np.arange(2, 9, 2)
array([2, 4, 6, 8])

You can also use np.linspace() to create an array with values that are spaced linearly in a specified interval:

>>> np.linspace(0, 10, num=5)
array([ 0. ,  2.5,  5. ,  7.5, 10. ])

Specifying your data type

While the default data type is floating point (np.float64), you can explicitly specify which data type you want using the dtype keyword.

>>> x = np.ones(2, dtype=np.int64)
>>> x
array([1, 1])

How to create a random array?

NumPy offers the random module to work with random numbers.

from numpy import random

Generate a random integer from 0 to 100:

>>> x = random.randint(100)
>>> x
24

Generate a 1-D array containing 5 random integers from 0 to 100:

>>> x=random.randint(100, size=(5))
>>> x
[34 77 42 77 72]

Generate a random float from 0 to 1:

>>> x = random.rand()
>>> x
0.08100820687742583

Generate a 1-D array containing 5 random floats:

>>> x = random.rand(5)
>>> x
[0.7659565 0.9967736 0.0398259 0.2213629 0.1414646]

Creating matrices

You can pass Python lists of lists to create a 2-D array (or “matrix”) to represent them in NumPy.

>>> data = np.array([[1, 2], [3, 4]])
>>> data

array([[1, 2],
       [3, 4]])

Most functions we have mentioned so far work for matrices as well. For example, here is how to generate a 2-D array with 3 rows, each row containing 5 random integers from 0 to 100:

>>> x = random.randint(100, size=(3, 5))
>>> x
[[80 54 19 74 65] 
 [26 60 69 34 25] 
 [50 16 53 84 90]]

Generate a 2-D array with 3 rows, each row containing 5 random numbers:

>>> x = random.rand(3, 5)
>>> x
[[0.03379952 0.78263517 0.9834899  0.47851523 0.02948659] 
 [0.36284007 0.10740884 0.58485016 0.20708396 0.00969559] 
 [0.88232193 0.86068608 0.75548749 0.61233486 0.06325663]]

Indexing and slicing

You can index and slice NumPy arrays in the same ways you can slice Python lists.

>>> data = np.array([1, 2, 3])

>>> data[1]
2

>>> data[0:2]
array([1, 2])

>>> data[1:]
array([2, 3])

>>> data[-2:]
array([2, 3])

You can visualize it this way:

You may want to take a section of your array or specific array elements to use in further analysis or additional operations. To do that, you’ll need to subset, slice, and/or index your arrays.

Indexing and slicing operations are useful when you’re manipulating matrices as well. You can then slice or index both dimensions:

>>> data = np.array([[1, 2], [3, 4]])
>>> data[0, 1]
2

>>> data[1:3]
array([[3, 4]])

>>> data[0:2, 0]
array([1, 3])

You can also index on a single dimension while keeping the other fixed:

>>> data[:, 1]
array([2, 4])

If you want to select values from your array that fulfil certain conditions, it’s straightforward with NumPy. For example, if you start with this array:

>>> a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

You can easily print all of the values in the array that are less than 5.

>>> print(a[a < 5])
[1 2 3 4]

You can also select, for example, numbers that are equal to or greater than 5, and use that condition to index an array.

>>> five_up = a[a >= 5]
[5 6 7 8 9 10 11 12]

You can select elements that are divisible by 2:

>>> divisible_by_2 = a[a % 2 == 0]
>>> print(divisible_by_2)
[2 4 6 8 10 12]

Or you can select elements that satisfy two conditions using the & and | operators:

>>> c = a[(a > 2) & (a < 11)]
>>> print(c)
[3 4 5 6 7 8 9 10]

This is called Boolean Indexing and can be extremely useful. This might look like magic, so let's break down why it works. First, you are aware of Booleans, and how you can produce a True or False output like so:

>>> a = 4
>>> print(a >= 3)
True

Well, similarly you can compare an array with a number, but instead of a single Boolean value, it will return a Boolean value for each element in the array:

>>> five_up = (a >= 5)
>>> print(five_up)
[[False False False False]
 [ True  True  True  True]
 [ True  True  True True]]
>>> print(five_up.dtype)
dtype('bool')

Wow! So we get back an array of the same shape as a but instead with True or False (and therefore datatype 'bool') as elements depending on whether the element in the same place satisfies the comparison. Then we can use that array to index the original array, which will only give back the elements where the index is True:

>>> five_up = (a >= 5)
>>> print(a[five_up])
[5  6  7  8  9 10 11 12]

Which is what we got before as well! This works only if the shapes of both the index and the array are the same. Let's discuss how to get the shape of an array next.

How do you know the shape and size of an array?

This section covers ndarray.ndim, ndarray.size, ndarray.shape

ndarray.ndim will tell you the number of axes, or dimensions, of the array.

ndarray.size will tell you the total number of elements of the array. This is the product of the elements of the array’s shape.

ndarray.shape will display a tuple of integers that indicate the number of elements stored along each dimension of the array. If, for example, you have a 2-D array with 2 rows and 3 columns, the shape of your array is (2, 3).

For example, if you create this array:

>>> array_example = np.array([[[0, 1, 2, 3],
...                            [4, 5, 6, 7]],
...
...                           [[0, 1, 2, 3],
...                            [4, 5, 6, 7]],
...
...                           [[0 ,1 ,2, 3],
...                            [4, 5, 6, 7]]])

To find the number of dimensions of the array, run:

>>> array_example.ndim
3

To find the total number of elements in the array, run:

>>> array_example.size
24

And to find the shape of your array, run:

>>> array_example.shape
(3, 2, 4)

Transposing and reshaping a matrix

This section covers arr.reshape(), arr.transpose(), arr.T

It’s common to need to transpose your matrices. NumPy arrays have the property T that allows you to transpose a matrix.

You may also need to switch the dimensions of a matrix. This can happen when, for example, you have a model that expects a certain input shape that is different from your dataset. This is where the reshape method can be useful. You simply need to pass in the new dimensions that you want for the matrix.

>>> data.reshape(2, 3)
array([[1, 2, 3],
       [4, 5, 6]])
>>> data.reshape(3, 2)
array([[1, 2],
       [3, 4],
       [5, 6]])

You can also use .transpose() to reverse or change the axes of an array according to the values you specify.

If you start with this array:

>>> arr = np.arange(6).reshape((2, 3))
>>> arr
array([[0, 1, 2],
       [3, 4, 5]])

You can transpose your array with arr.transpose().

>>> arr.transpose()
array([[0, 3],
       [1, 4],
       [2, 5]])

You can also use arr.T:

>>> arr.T
array([[0, 3],
       [1, 4],
       [2, 5]])

Reshaping and flattening multidimensional arrays

This section covers .flatten(), ravel()

There are two popular ways to flatten an array: .flatten() and .ravel(). The primary difference between the two is that the new array created using ravel() is actually a reference to the parent array (i.e., a “view”). This means that any changes to the new array will affect the parent array as well. Since ravel does not create a copy, it’s memory efficient.

If you start with this array:

>>> x = np.array([[1 , 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

You can use flatten to flatten your array into a 1D array.

>>> x.flatten()
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])

When you use flatten, changes to your new array won’t change the parent array.

For example:

>>> a1 = x.flatten()
>>> a1[0] = 99
>>> print(x)  # Original array
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
>>> print(a1)  # New array
[99  2  3  4  5  6  7  8  9 10 11 12]

But when you use ravel, the changes you make to the new array will affect the parent array.

For example:

>>> a2 = x.ravel()
>>> a2[0] = 98
>>> print(x)  # Original array
[[98  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
>>> print(a2)  # New array
[98  2  3  4  5  6  7  8  9 10 11 12]

Creating new versions of existing arrays

This section covers np.vstack(), np.hstack(), np.concatenate, np.hsplit(), .view(), copy()

Stacking of arrays

You can combine arrays by stacking them, both vertically and horizontally. Let’s say you have two arrays, a1 and a2:

>>> a1 = np.array([[1, 1],
...                [2, 2]])

>>> a2 = np.array([[3, 3],
...                [4, 4]])

You can stack them vertically with vstack:

>>> np.vstack((a1, a2))
array([[1, 1],
       [2, 2],
       [3, 3],
       [4, 4]])

Or stack them horizontally with hstack:

>>> np.hstack((a1, a2))
array([[1, 1, 3, 3],
       [2, 2, 4, 4]])

Similarly, you could concatenate them with np.concatenate().

>>> np.concatenate((a, b))
array([1, 2, 3, 4, 5, 6, 7, 8])

Or, if you start with these arrays:

>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6], [7,8]])

You can concatenate them with:

>>> np.concatenate((a, b), axis=0)
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])

Or:

>>> np.concatenate((a, b), axis=1)
array([[1, 2, 5, 6],
       [3, 4, 7, 8]])

In 2D this achieves the same as with hstack or vstack but if you ever need it, concatenate also works for higher dimensions!

Shallow and deep copies

You can use the view method to create a new array object that looks at the same data as the original array (a shallow copy).

Views are an important NumPy concept! NumPy functions, as well as operations like indexing and slicing, will return views whenever possible. This saves memory and is faster (no copy of the data has to be made). However it’s important to be aware of this - modifying data in a view also modifies the original array!

Let’s say you create this array:

>>> a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

Now we create an array b1 by slicing a and modify the first element of b1. This will modify the corresponding element in a as well!

>>> b1 = a[0, :]
>>> b1
array([1, 2, 3, 4])

>>> b1[0] = 99
>>> b1
array([99,  2,  3,  4])

>>> a
array([[99,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

Using the copy method will make a complete copy of the array and its data (a deep copy). To use this on your array, you could run:

>>> b2 = a.copy()

Array operations

We have seen how to create an index arrays and some basic ways to transform them. Next to these, there is a large amount of built-in array operations NumPy that can be used to modify arrays and gain insight in their data. We will cover some of those operations here, the ones that are commonly used. Do keep in mind that this is just touching the surface: NumPy is a huge library and many things are built-in. If you wonder if a function exists, Google it, and chances are you might find it!

Basic array operations

This section covers addition, subtraction, multiplication, division

Once you’ve created your arrays, you can start to work with them. Let’s say, for example, that you’ve created two arrays, one called “data” and one called “ones”

You can add the arrays together with the plus sign.

>>> data = np.array([1, 2])
>>> ones = np.ones(2, dtype=int)
>>> data + ones
array([2, 3])

You can, of course, do more than just addition!

>>> data - ones
array([0, 1])
>>> data * data
array([1, 4])
>>> data / data
array([1., 1.])

Broadcasting

There are times when you might want to carry out an operation between an array and a single number (also called an operation between a vector and a scalar) or between arrays of two different sizes. For example, your array (we’ll call it “data”) might contain information about distance in miles but you want to convert the information to kilometres. You can perform this operation with:

>>> data = np.array([1.0, 2.0])
>>> data * 1.6
array([1.6, 3.2])

NumPy understands that the multiplication should happen with each cell. That concept is called broadcasting. Broadcasting is a mechanism that allows NumPy to perform operations on arrays of different shapes. The dimensions of your array must be compatible, for example, when the dimensions of both arrays are equal or when one of them is 1. If the dimensions are not compatible, you will get a ValueError.

More complex array operations

This section covers maximum, minimum, sum, mean, product, standard deviation, and more

NumPy also performs aggregation functions. In addition to min, max, and sum, you can easily run mean to get the average, prod to get the result of multiplying the elements together, std to get the standard deviation, and more.

>>> data.max()
2.0
>>> data.min()
1.0
>>> data.sum()
3.0

Let’s start with this array, called “a”

>>> a = np.array([[0.45053314, 0.17296777, 0.34376245, 0.5510652],
...               [0.54627315, 0.05093587, 0.40067661, 0.55645993],
...               [0.12697628, 0.82485143, 0.26590556, 0.56917101]])

It’s very common to want to aggregate along a row or column. By default, every NumPy aggregation function will return the aggregate of the entire array. To find the sum or the minimum of the elements in your array, run:

Or:

You can specify on which axis you want the aggregation function to be computed. For example, you can find the minimum value within each column by specifying axis=0.

>>> a.min(axis=0)
array([0.12697628, 0.05093587, 0.26590556, 0.5510652 ])

The four values listed above correspond to the number of columns in your array. With a four-column array, you will get four values as your result.

You can aggregate matrices the same way you aggregated vectors:

>>> data.max()
4
>>> data.min()
1
>>> data.sum()
10

You can aggregate all the values in a matrix and you can aggregate them across columns or rows using the axis parameter:

>>> data.max(axis=0)
array([3, 4])
>>> data.max(axis=1)
array([2, 4])

Similarly to arrays, you can add and multiply matrices using arithmetic operators if you have two matrices that are the same size:

>>> data = np.array([[1, 2], [3, 4]])
>>> ones = np.array([[1, 1], [1, 1]])
>>> data + ones
array([[2, 3],
       [4, 5]])

You can do these arithmetic operations on matrices of different sizes, but only if one matrix has only one column or one row. In this case, NumPy will use its broadcast rules for the operation.

>>> data = np.array([[1, 2], [3, 4], [5, 6]])
>>> ones_row = np.array([[1, 1]])
>>> data + ones_row
array([[2, 3],
       [4, 5],
       [6, 7]])

Be aware that when NumPy prints N-dimensional arrays, the last axis is looped over the fastest while the first axis is the slowest.

Sorting elements

This section covers np.sort()

Sorting an element is simple with np.sort(). You can specify the axis, kind, and order when you call the function.

If you start with this array:

>>> arr = np.array([2, 1, 5, 3, 7, 4, 6, 8]

You can quickly sort the numbers in ascending order with:

>>> np.sort(arr)
array([1, 2, 3, 4, 5, 6, 7, 8])

If you start with these arrays:

>>> a = np.array([1, 2, 3, 4])
>>> b = np.array([5, 6, 7, 8])

Further NumPy reading

Most of the visualisations used in this material section is from this illustrated NumPy guide. If you would like to read up some more, you can check it out for a slightly different explanation. Do note that in contains more content than we expect from you to know.

PANDAS - What is Pandas?

Pandas is a Python library used for working with data sets.

It has functions for analyzing, cleaning, exploring, and manipulating data.

The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis" and was created by Wes McKinney in 2008.

Why Use Pandas?

Pandas allows us to analyze big data and make conclusions based on statistical theories.

Pandas can clean messy data sets, and make them readable and relevant.

Relevant data is very important in data science.

Intro to data structures

We’ll start with a quick, non-comprehensive overview of the fundamental data structures in pandas to get you started. The fundamental behavior about data types, indexing, and axis labeling / alignment apply across all of the objects. To get started, import NumPy and load pandas into your namespace:

import numpy as np

import pandas as pd

Series

Series is a one-dimensional labelled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). The axis labels are collectively referred to as the index.

A Pandas Series is like a column in a table. It is a one-dimensional array holding data of any type.

The basic method to create a Series is to call:

s = pd.Series(data, index=index)

Create a simple Pandas Series from a list:

a = [1, 7, 2]
s = pd.Series(a)
s

If nothing else is specified, the values are labeled with their index number. First value has index 0, second value has index 1 etc.

This label can be used to access a specified value.

Create you own labels:

a = [1, 7, 2]
s = pd.Series(a, index = ["x", "y", "z"])
s

Create a simple Pandas Series from a dictionary:

d = {"b": 1, "a": 0, "c": 2}
s = pd.Series(d)
s

If an index is passed, the values in data corresponding to the labels in the index will be pulled out:

>>> d = {"a": 0.0, "b": 1.0, "c": 2.0}
>>> pd.Series(d)

a    0.0
b    1.0
c    2.0
dtype: float64

>>> pd.Series(d, index=["b", "c", "d", "a"])
 
b    1.0
c    2.0
d    NaN
a    0.0
dtype: float64

NaN (not a number) is the standard missing data marker used in pandas.

If data is a scalar value, an index must be provided. The value will be repeated to match the length of index:

>>> pd.Series(5.0, index=["a", "b", "c", "d", "e"])
 
a    5.0
b    5.0
c    5.0
d    5.0
e    5.0
dtype: float64

Create a simple Pandas Series from an ndarray:

If data is an ndarray, index must be the same length as data. If no index is passed, one will be created having values [0, ..., len(data) - 1]

>>> s = pd.Series(np.random.randn(5), index=["a", "b", "c", "d", "e"])
>>> s
 
a    0.469112
b   -0.282863
c   -1.509059
d   -1.135632
e    1.212112
dtype: float64


>>> s.index

Index(['a', 'b', 'c', 'd', 'e'], dtype='object')


>>> pd.Series(np.random.randn(5))
 
0   -0.173215
1    0.119209
2   -1.044236
3   -0.861849
4   -2.104569
dtype: float64

Indexing

Series is ndarray-like:

Series acts very similarly to a ndarray, and is a valid argument to most NumPy functions. However, operations such as slicing will also slice the index.

>>> from numpy import random
>>> s = pd.Series(random.randint(100, size=(5)), index=["a", "b", "c", "d", "e"])
>>> s

a    33
b    54
c    86
d    73
e    14
dtype: int32

>>> s[0]
33

>>> s[:3]
a    33
b    54
c    86
dtype: int32


>>> s[s > s.median()]
c    86
d    73
dtype: int32


>>> s[[4, 3, 1]]
e    14
d    73
b    54
dtype: int32

Series is dict-like:

A Series is like a fixed-size dict in that you can get and set values by index label:

>>> s["a"]
33


>>> s["e"] = 99
>>> s
a    33
b    54
c    86
d    73
e    99
dtype: int32


>>> "f" in s
False

A few attributes of the series:

An example:

>>> my_series = pd.Series({"United Kingdom":"London", "India":"New Delhi", 
                       "United States":"Washington", "Belgium":"Brussels"})
>>> my_series

United Kingdom        London
India              New Delhi
United States     Washington
Belgium             Brussels
dtype: object

dtype -Return the dtype object of the underlying data. Pandas will default to the object datatype ('o') for strings:

>>> my_series.dtype
dtype('O')

shape -Return a tuple of the shape of the underlying data.

>>> my_series.shape
(4,)

axes- Return a list of the row axis labels.

>>> my_series.axes
[Index(['United Kingdom', 'India', 'United States', 'Belgium'], dtype='object')]

>>> type(my_series.axes)
listthon

index -The index (axis labels) of the Series.

>>> my_series.index
Index(['United Kingdom', 'India', 'United States', 'Belgium'], dtype='object')

>>> type(my_series.index)
pandas.core.indexes.base.Index

values -Return Series as ndarray or ndarray-like depending on the dtype.

>>> my_series.values
array(['London', 'New Delhi', 'Washington', 'Brussels'], dtype=object)

keys() - Return alias for index.

>>> my_series.keys()
Index(['United Kingdom', 'India', 'United States', 'Belgium'], dtype='object')

Simple Concatenation with pd.concat

pd.concat() can be used for a simple concatenation of Series or DataFrame objects, just as np.concatenate() can be used for simple concatenations of arrays.

Concatenating 2 Series with default parameters:

>>>  ser1 = pd.Series(['A', 'B', 'C'], index=[1, 2, 3])
>>>  ser2 = pd.Series(['D', 'E', 'F'], index=[4, 5, 6])
>>>  pd.concat([ser1, ser2])

1    A
2    B
3    C
4    D
5    E
6    F
dtype: object

Concatenating 2 series horizontally with index = 1:

>>> ser1 = pd.Series(['A', 'B', 'C'])
>>> ser2 = pd.Series(['D', 'E', 'F'])  
>>> pd.concat([ser1, ser2], axis = 1)


  0 1
0	A	D
1	B	E
2	C	F

Concatenate two or more Series with append()

>>> ser1 = pd.Series(['A', 'B', 'C'])
>>> ser2 = pd.Series(['D', 'E', 'F'])

>>> ser1.append(ser2)

0    A
1    B
2    C
0    D
1    E
2    F
dtype: object
>>> ser1 = pd.Series(['A', 'B', 'C'])
>>> ser2 = pd.Series(['D', 'E', 'F'])

>>> ser1.append(ser2, ignore_index=True) 
###ignore_index: (If True, the resulting axis will be labeled 0, 1, …, n - 1)

0    A
1    B
2    C
3    D
4    E
5    F
dtype: object

Last updated

#338:

Change request updated