The post Transpose Matrix using Python appeared first on PyShark. The post Transpose Matrix using Python first appeared on Python-bloggers.]]>

Want to share your content on python-bloggers? click here.

In this article we will discuss the steps and intuition for calculating the transpose of a matrix using Python.

**Table of contents**

**Books I recommend:**

- Python Crash Course
- Automate the Boring Stuff with Python
- Beyond the Basic Stuff with Python
- Serious Python

Transpose of a matrix is one of the fundamental topics in linear algebra, and also one of the simplest ones to understand.

To continue following this tutorial we will need the following Python library: numpy.

If you don’t have them installed, please open “Command Prompt” (on Windows) and install them using the following code:

pip install numpy

The transpose of a matrix, in linear algebra, is an operator which rotates the matrix around its main diagonal.

In simple words, the rows become columns, and columns become rows of a matrix.

**Square matrix example**

Given some matrix \(A\):

$$A = \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{bmatrix}$$

Its transpose is:

$$A^T = \begin{bmatrix} 1 & 4 & 7 \\ 2 & 5 & 8 \\ 3 & 6 & 9 \end{bmatrix}$$

The steps of transposition are quite simple. First we find the main diagonal (highlighted in red below), and then we essentially flip the matrix around it, and that’s how we get the transpose:

**Non-square matrix example**

Given some matrix \(A\) of \(3 \times 2\) dimension (can be any other dimension):

$$A = \begin{bmatrix} 1 & 2 \\ 3 & 4 \\ 5 & 6 \end{bmatrix}$$

Its transpose is a matrix of \(2 \times 3\) dimension (in this case):

$$A^T = \begin{bmatrix} 1 & 3 & 5 \\ 2 & 4 & 6 \end{bmatrix}$$

The steps of transposition are the same as for the square matrix. First we find the main diagonal (highlighted in red below), and then we essentially flip the matrix around it, and that’s how we get the transpose:

We can generalize the matrix transpose steps as:

Given matrix \(A\) of \(m \times n \) dimension, it’s transpose is matrix \(A^T\) of \(n \times m\) dimension.

We are essentially always rotating the matrix around the main diagonal.

Note that the transpose of a diagonal matrix will be the same matrix.

In order to create an identity matrix in Python we will use the numpy library. And the first step will be to import it:

import numpy as np

Numpy has a lot of useful functions, and for this operation we will use the transpose() function which will transpose a given matrix.

Recall that in Python matrices are constructed as arrays. So the next step will be to define the input matrix:

A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(A)

The input matrix should be:

[[1 2 3] [4 5 6] [7 8 9]]

The final step is to transpose the matrix using Python:

A_T = np.transpose(A) print(A_T)

And you should get:

[[1 4 7] [2 5 8] [3 6 9]]

which is exactly the same answer as in the previous section.

In this article we discussed the steps and intuition for calculating a transpose of a matrix using Python.

Feel free to leave comments below if you have any questions or have suggestions for some edits and check out more of my Linear Algebra articles.

The post Transpose Matrix using Python appeared first on PyShark.

To **leave a comment** for the author, please follow the link and comment on their blog: ** PyShark**.

Want to share your content on python-bloggers? click here.

Want to share your content on python-bloggers? click here.

- Conduct rigorous data analysis that is easy to reproduce and share with colleagues
- Create beautiful visualizations that aren’t available in basic Excel and Power BI
- Collaborate more effectively with engineers, developers, data scientists and other technical professionals
- Signal to employers that you can work with a variety of programming tools
- Take advantage of Power BI’s supported integration with Python and R
- Prepare for Excel’s likely future supported integration with Python

If you’re a financial analyst looking to level up your data analysis skills, this is the workshop and book for you. After attending this class, you’ll be in great shape to explore advanced analytics in Excel, Python and R.

My number one goal is to make you a well-rounded analyst that will be able to handle any project that comes your way. To that end, I the course comes with the usual offerings plus supplemental goodies:

- Class recording
- Demo notes and handouts
- 3-hour video course on Excel Power Query, yours to enjoy any time
- A signed paperback copy of
*Advancing into Analytics*to read after class

- Please have Excel 2010 or greater for desktop installed prior to class
- It is recommended to attend this workshop on a Windows machine.
- Basic to intermediate Excel knowledge: sorting and filtering, IF() statements, SUMIF(), COUNTIF(), PivotTables, VLOOKUP().
- No other preparation is needed. I’ll send you the course materials at the time of class.
- We will be using cloud-based instances of R and Python, so you don’t need to have these installed for the class. You will learn in the book how to install them on your computer.

The class is scheduled for 70 minutes. In that time, we’ll be working through a real-world dataset of housing prices from Excel to R and Python:

- Exploring relationships in the data using Excel
- Confirming and reporting on them in R
- Building a linear regression model in Python

- A copy of the book will be mailed to the address you provide during signup. The surcharge for international orders is to accommodate for shipping.
- Information on all other resources will be provided during the event.

Because I am sending you a personalized copy of the book, I can’t process refunds. All sales are final.

To **leave a comment** for the author, please follow the link and comment on their blog: ** Stringfest Analytics**.

Want to share your content on python-bloggers? click here.

The post Create Diagonal Matrix using Python appeared first on PyShark. The post Create Diagonal Matrix using Python first appeared on Python-bloggers.]]>

Want to share your content on python-bloggers? click here.

In this article we will discuss the steps and intuition for creating the diagonal matrix and show examples using Python.

**Table of contents**

- Introduction
- Diagonal matrix explained
- Create diagonal matrix using Python
- Extract diagonal from matrix using Python
- Conclusion

**Books I recommend:**

- Python Crash Course
- Automate the Boring Stuff with Python
- Beyond the Basic Stuff with Python
- Serious Python

The diagonal matrix (\(D\)) is most often seen in linear algebra expressions that involve the identity matrices.

To continue following this tutorial we will need the following Python library: numpy.

If you don’t have them installed, please open “Command Prompt” (on Windows) and install them using the following code:

pip install numpy

We are already familiar with the identity matrix and some of its properties, and it actually is a special case of a diagonal matrix.

A diagonal matrix is a matrix (usually a square matrix of order \(n\)) filled with values on the main diagonal and zeros everywhere else.

Here are a few examples:

$$D_1 = \begin{bmatrix} 3 \end{bmatrix}$$

$$D_2 = \begin{bmatrix} 3 & 0 \\ 0 & 2 \end{bmatrix}$$

$$D_3 = \begin{bmatrix} 3 & 0 & 0 \\ 0 & 2 & 0 \\ 0 & 0 & 5 \end{bmatrix}$$

and so on for the larger dimensions.

Graphically, the \(D_2\) matrix simply represents the scaled base vectors:

$$\vec{d}_1 = (3, 0)$$

$$\vec{d}_2 = (0, 2)$$

There are usually two main use cases for the diagonal matrix:

- Creating a diagonal matrix – implies taking a vector and creating a matrix where the values from a vector become the main diagonal of a matrix.
- Extracting a diagonal from a matrix – implies finding the main diagonal in a given matrix.

In order to create a diagonal matrix using Python we will use the numpy library. And the first step will be to import it:

import numpy as np

Numpy has a lot of useful functions, and for this operation we will use the diag() function. This function is particularly interesting, because if we pass a 1-D array into it, it will return a 2-D array (or a matrix) with the vector values on its \(k\)-th diagonal (\(k\)=0 for the main diagonal).

Now let’s create some 1-D array (or a vector):

v = [3, 2, 5]

and create a matrix with \(v\) on the main diagonal:

D = np.diag(v) print(D)

And you should get:

[[3 0 0] [0 2 0] [0 0 5]]

which is a diagonal matrix with values on the main diagonal and zeros everywhere else.

In order to extract a diagonal from a matrix using Python we will use the numpy library. And the first step will be to import it:

import numpy as np

Numpy has a lot of useful functions, and for this operation we will use the diag() function. This function is particularly interesting, because if we pass a 2-D array into it, it will return its \(k\)-th diagonal (\(k\)=0 for the main diagonal).

Now let’s create some 3×3 matrix:

A = np.array([[3, 1, 4], [0, 2, 7], [8, 9, 5]])

and extract it’s main diagonal:

d = np.diag(A) print(d)

And you should get:

[3 2 5]

which are exactly the values on the main diagonal of the matrix.

In this article we discussed the steps and intuition for creating the diagonal matrix, as well as extracting a diagonal from a matrix using Python.

Feel free to leave comments below if you have any questions or have suggestions for some edits and check out more of my Linear Algebra articles.

The post Create Diagonal Matrix using Python appeared first on PyShark.

To **leave a comment** for the author, please follow the link and comment on their blog: ** PyShark**.

Want to share your content on python-bloggers? click here.

The post Calculate Hadamard Product using Python appeared first on PyShark. The post Calculate Hadamard Product using Python first appeared on Python-bloggers.]]>

Want to share your content on python-bloggers? click here.

In this article we will discuss the steps and intuition for calculating the Hadamard product with examples using Python.

**Table of contents**

Hadamard product of two matrices calculation is very similar to the process of matrix addition, but the operation itself is multiplication.

To continue following this tutorial we will need the following Python library: numpy.

If you don’t have them installed, please open “Command Prompt” (on Windows) and install them using the following code:

pip install numpy

Hadamard product is also known as the element-wise multiplication or element-wise product.

While Hadamard product performs the multiplication operation, it is different from the matrix multiplication (matrix product) which we usually see in linear algebra.

Hadamard product can be computed only for two matrices of the same dimension (2×2, 3×3, and so on). This operation produces a matrix which is the same dimension as the input matrices:

For matrices \(A\) and \(B\) (of the same dimension), the Hadamard product can be computed as:

$$C = A \circ B$$

where \(\circ\) is the element-wise multiplication, and not the \(\cdot\) multiplication.

Let’s consider two sample matrices \(A\) and \(B\):

$$A = \begin{bmatrix} a_{11} & a_{12} & a_{13} \\ a_{21} & a_{22} & a_{23} \\ a_{31} & a_{32} & a_{33} \end{bmatrix}$$

$$B = \begin{bmatrix} b_{11} & b_{12} & b_{13} \\ b_{21} & b_{22} & b_{23} \\ b_{31} & b_{32} & b_{33} \end{bmatrix}$$

Calculating the Hadamard product (element-wise multiplication):

$$C = A \circ B = \begin{bmatrix} a_{11} & a_{12} & a_{13} \\ a_{21} & a_{22} & a_{23} \\ a_{31} & a_{32} & a_{33} \end{bmatrix} \circ \begin{bmatrix} b_{11} & b_{12} & b_{13} \\ b_{21} & b_{22} & b_{23} \\ b_{31} & b_{32} & b_{33} \end{bmatrix} = \begin{bmatrix} a_{11} b_{11} & a_{12} b_{12} & a_{13} b_{13} \\ a_{21} b_{21} & a_{22} b_{22} & a_{23} b_{23} \\ a_{31} b_{31} & a_{32} b_{32} & a_{33} b_{33} \end{bmatrix} $$

The process is very similar to matrix addition or matrix subtraction, except here we are multiplying the elements of the matrices.

For an illustrative example, we will use the same matrices \(A\) and \(B\) as we used in the matrix multiplication article:

$$A = \begin{bmatrix} 1 & 6 \\ 2 & 3 \end{bmatrix}$$

$$B = \begin{bmatrix} 5 & 1 \\ 3 & 2 \end{bmatrix}$$

Calculating the Hadamard product:

$$A \circ B = \begin{bmatrix} 1 & 6 \\ 2 & 3 \end{bmatrix} \circ \begin{bmatrix} 5 & 1 \\ 3 & 2 \end{bmatrix} = \begin{bmatrix} 1 \times 5 & 6 \times 1 \\ 2 \times 3 & 3 \times 2 \end{bmatrix} = \begin{bmatrix} 5 & 6 \\ 6 & 6 \end{bmatrix}$$

In order to calculate the Hadamard product (element-wise matrix multiplication) in Python we will use the numpy library. And the first step will be to import it:

import numpy as np

Numpy has a lot of useful functions, and for this operation we will use the multiply() function which multiplies arrays element-wise.

Recall that in Python matrices are constructed as arrays, and that matrices need to be of the same dimension to be added. And the next step will be to define the input matrices.

We are going to use the same 2×2 matrices as in the previous section:

A = np.array([[1, 6], [2, 3]]) B = np.array([[5, 1], [3, 2]])

Now that we have the required matrices, we can easily calculate the Hadamard product resulting from the matrix element-wise multiplication:

C = np.multiply(A, B) print(C)

And you should get:

[[5 6] [6 6]]

which is exactly the same output as in our example where we calculated it manually.

In this article we discussed the intuition and steps for Hadamard product, as well as shown complete examples using Python.

Feel free to leave comments below if you have any questions or have suggestions for some edits and check out more of my Linear Algebra articles.

The post Calculate Hadamard Product using Python appeared first on PyShark.

To **leave a comment** for the author, please follow the link and comment on their blog: ** PyShark**.

Want to share your content on python-bloggers? click here.

The post Matrix Subtraction Explained (with Python Examples) appeared first on PyShark. The post Matrix Subtraction Explained (with Python Examples) first appeared on Python-bloggers.]]>

Want to share your content on python-bloggers? click here.

In this article we will discuss the steps and intuition for matrix addition with examples and perform matrix subtraction in Python.

**Table of contents**

In this article we explain the intuition and steps of matrix subtraction.

The examples used are fairly simple and don’t require even a calculator. The logic is very similar to the process of matrix additions as well. However, the approaches learnt in this article can be applied on more complex matrix subtractions.

We also explore how quick and easy it is to perform matrix addition using Python.

To continue following this tutorial we will need the following Python library: numpy.

pip install numpy

A matrix can be subtracted from another matrix if and only if they have the same dimension (both are 2×2, 3×3, and so on).

For an intuitive example let’s consider 2 farmers who both have some apples and some grapes in storage. We can represent this as a table:

Storage |
Farmer 1 | Farmer 2 |

Apples | 3 | 2 |

Grapes | 7 | 5 |

which can also be simply shown in a matrix:

$$A = \begin{bmatrix} 3 & 2 \\ 7 & 5 \end{bmatrix}$$

These two farmers then went to the market and sold some fruit. The amount of fruit they sold can also be represented as a table:

Sold |
Farmer 1 | Farmer 2 |

Apples | 2 | 1 |

Grapes | 1 | 3 |

which can also be simply shown in a matrix:

$$B = \begin{bmatrix} 2 & 1 \\ 1 & 3 \end{bmatrix}$$

Once the market closes, they calculate how much the new total number of fruit in the storage is after they sold some of it. And they do it by just subtracting the sold fruit number to get:

Total |
Farmer 1 | Farmer 2 |

Apples | 1 | 1 |

Grapes | 6 | 2 |

Farmer 1 subtracted apples from apples (2-1=1) and grapes from grapes (7-1=6). Farmer 2 did the same thing, and got 1 (2-1) and 2 (5-3) respectively.

Now let’s do the same thing in matrix form:

$$C = A – B = \begin{bmatrix} 3 & 2 \\ 7 & 5 \end{bmatrix} – \begin{bmatrix} 2 & 1 \\ 1 & 3 \end{bmatrix} = \begin{bmatrix} 3-2 & 2-1 \\ 7-1 & 5-3 \end{bmatrix} = \begin{bmatrix} 1 & 1 \\ 6 & 2 \end{bmatrix}$$

And we see that matrix \(C\) has the same values as the table with totals above it.

We can further generalize this approach for a \(m \times n\) dimension matrix:

$$A – B = \begin{bmatrix} a_{11} & a_{12} & \dots & a_{1n} \\ a_{21} & a_{22} & \dots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1} & a_{m2} & \dots & a_{mn} \end{bmatrix} – \begin{bmatrix} b_{11} & b_{12} & \dots & b_{1n} \\ b_{21} & b_{22} & \dots & b_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ b_{m1} & b_{m2} & \dots & b_{mn} \end{bmatrix} = \\[50pt] = \begin{bmatrix} a_{11}-b_{11} & a_{12}-b_{12} & \dots & a_{1n}-b_{1n} \\ a_{21}-b_{21} & a_{22}-b_{22} & \dots & a_{2n}-b_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1}-b_{m1} & a_{m2}-b_{m2} & \dots & a_{mn}-b_{mn} \end{bmatrix}$$

In order to perform the matrix vector multiplication in Python we will use the numpy library. And the first step will be to import it:

import numpy as np

Numpy has a lot of useful functions, and for this operation we will use the subtract() function which subtracts arrays element-wise.

Recall that in Python matrices are constructed as arrays, and that matrices need to be of the same dimension to be subtracted. And the next step will be to define the input matrices.

We are going to use the same 2×2 matrices as in the previous section:

A = np.array([[3, 2], [7, 5]]) B = np.array([[2, 1], [1, 3]])

Now that we have the required matrices, we can easily calculate the matrix resulting from the matrix subtraction:

C = np.subtract(A, B) print(C)

And you should get:

[[1 1] [6 2]]

which is exactly the same output as in our example where we calculated it manually.

In this article we discussed the intuition and steps for matrix subtraction, as well as shown complete examples using Python.

The post Matrix Subtraction Explained (with Python Examples) appeared first on PyShark.

To **leave a comment** for the author, please follow the link and comment on their blog: ** PyShark**.

Want to share your content on python-bloggers? click here.

Want to share your content on python-bloggers? click here.

This tutorial has been borne out of the ability to port my development environments around. Most times I have to create requirements files to specify the dependent packages to be created in my virtual environments.

To learn how to create virtual environments, see below:

- Anaconda: https://hutsons-hacks.info/creating-and-replicating-an-anaconda-environment-from-a-yaml-file

The question I get asked all the time is how to create a file that will allow me to install all the dependencies from specific environments, including pip packages versions into one file.

For us in the know – we solve this by creating a requirements.txt file to be used in our projects. This file essentially takes all the currently loaded packages, that made your file/script work on one machine and packages them up to make your script/application work on another machine. This is the primary purpose of why we would want to create a file like this, and it is a really powerful concept.

A couple of nuances to the environment creation tutorials have been linked here. These delve into if you want a virtual environment for a specific installation of Python, then you will need to follow these sub-points.

Go to Anaconda Navigator > Environments > Create, then as below:

To do the equivalent in code, follow these steps:

- Open Terminal or Powershell
- Type the following command to create a new virtual environment. You will be prompted to install packages to create new environment:

conda create -n version_of_python_venv python=3.9.7 anaconda

To do this in pip, there is no visual option, the best approach I have found to do this is outlined in these steps:

- Download the specific version of Python you need to your machine e.g. for 3.7.9: https://www.python.org/downloads/release/python-379/
- Install the Python executable file. I recommend the default settings here, and no need to add to PATH system variables
- Open your terminal / command prompt / bash or whatever window you have on your operating system.
- Next we will need to install a package called virtualenv to make this work. Follow the script below:

pip install virtualenv

We are nearly there. To recap, up to this point you need to have carried out the above sub steps and you should have the virtualenv package installed from pip. The final steps are to create the virtual environment and get going:

- Create the virtual environment in your favourite brand of terminal using the below command:

pip install virtualenv

2. Next we want to see where our Python version is installed:

where python

3. This will print where the Python.exe is stored, as we will need this when we are creating a virtual environment. Next, we then make a directory where the virtual environment will be stored, to do this in code we can use the mkdir command in the command prompt:

mkdir py_venvs

4. Next, I will change the directory to my new folder just created:

cd py_venvs

5. Now it is time to create my virtual environment with a specific version of python:

python -m virtualenv -p="C:\Users\garyh\AppData\Local\Programs\Python\Python37\python.exe" py37_venv

To break this down:

- The python -m switch indicates to create a new virtual environment
- We call the virtualenv package we installed in pip
- The -p switch says I want to use my version locally in Python to create a new virtual environment, as the previous tutorials will create the virtual environment based off the newest version of Python, and this is not what we always want

A great tutorial on how to do this on a macOS can be found here.

This is very straightforward in a Python virtual environment, firstly you will need to set up a virtual environment, otherwise, you will be printing all the packages that reside in the base installation of Python.

Next, follow these steps:

- Activate your virtual environment. My new virtual environment will be located in my py_venv folder I created in the previous step. This will depend on what you called the virtual environment and which folder you stored it in:

cd py_venv # Activate the environment .\py37_venv\Scripts\activate.bat

This says look relative for a virtual environment named **py37_venv **and then navigate to the Python scripts folder and use the activate batch script, if this is successful you should see the virtual environment become active:

2. Now, I will use the following command to export out the requirements.txt to be used when we are creating new virtual environments:

pip freeze > requirements.txt

This will simply list all the installations on that specific virtual environment. This is really useful, as we can now use this to set up a completely new virtual environment based on the installed packages and the same Python version. The theory is – everything should work the same as it does on my local machine, as they have been tested under the same Python package versions.

We will practice and create another virtual environment, with a specific Python version, in the virtual environment folder I have been working in. The only things that will change for you are the folder names and whatever you decide to call your virtual environment:

cd C:\Users\garyh\Documents\py_venvs # Create a new environment that we will use to install the requirements.txt to python -m virtualenv -p="C:\Users\garyh\AppData\Local\Programs\Python\Python37\python.exe" rep_of_py37_venv # Activate the new virtual environment .\rep_of_py37_venv\Scripts\activate.bat # Virtual environment will be active = (rep_of_py37_venv) pip install -r requirements.txt

This script will navigate to where the environment needs to be created, create the new environment in the folder, activate the environment and then use the requirements.txt stored in the top level folder to create the environment with the same packages as the previous environment that we used pip list on:

Once this is completed your setup will look exactly the same as your original environment. This is how you use a requirements.txt, or whatever you call the .txt file to install all the same dependencies as before.

I have created a supporting YouTube video to solidify this content. I hope you find the video hereunder useful for these purposes:

If you like this content, please remember to subscribe and give the video a like. I really enjoy putting these together and it helps when I get nice comments and feedback.

The video has some coding errors, and I sometimes think this:

To **leave a comment** for the author, please follow the link and comment on their blog: ** Python – Hutsons-hacks**.

Want to share your content on python-bloggers? click here.

Want to share your content on python-bloggers? click here.

Python oftentimes leaves you with options, and quotes are no exception. What are the differences between Python single and double quotes? Which one should you use? When does one have an edge over the other? What are triple quotes? It's easy to get confused if you're a beginner.

You see, Python is a lot different from, let's say Java. In Java, you must use double quotes for strings, and are only allowed to use single quotes for characters. That's not the deal with Python. You have much more flexibility than in statically-typed languages. **But is it actually a good thing?** Continue reading to find out.

Don't feel like reading? Watch my video instead:

In Python, it's a best practice to use single quotes to surround small and short strings, such as string literals or identifiers. But here's the deal – it's not a requirement. You can write entire paragraphs and articles inside single quotes.

Here are a couple of examples:

name = 'Bob' print(name) channel = 'Better Data Science' print(channel) paragraph = 'Bob likes the content on Better Data Science. Bob is cool. Be like Bob.' print(paragraph)

There's no character limit set for the content between single quotes, but there are a few gotchas you'll inevitably run into. The first one is a quotation mark inside a string.

The English language is full of single quotation marks (apostrophes). For example, I can write *we are* or *we're*, and both represent the same thing. Opting for the second option is problematic if you want to use single quotes to surround strings in Python:

print('We're going skiing this winter.')

Python thinks the string ends after `We`

, so everything after it is considered a syntactical error. You can easily spot errors like these in code editors, as the part after `We`

is colored differently.

There are three ways around it:

**Stop using contractions**(*we are*->*we're*) – Not practical at all.**Escape a string**– A possibility we'll explore next.**Use double quotation**– Something we'll cover later.

The main idea behind escaping a string is preventing certain characters from being used as a part of the programming language. For example, we don't want the apostrophe treated as a quotation mark.

In Python, you can use the backslash (`\`

) sign to escape a string character:

print('We\'re going skiing this winter.')

That's cool, but backslash is often used as a literal character in strings – for example, to represent a path on a computer. Let's see what happens if you try to print a path using the escape character:

print('C:\Users\Bob')

Probably not what you wanted to see. As it turns out, you can escape the escape character in two ways:

**By using a raw string**– Write`r`

before the first quotation mark.**Use double backslash**– This will essentially escape the escape character.

Here's how to use both:

print(r'C:\Users\Bob') print('C:\\Users\\Bob')

These two apply both for strings surrounded with single and double quotes. We haven't covered double quotes yet, so let's do that next.

It's considered a best practice to use double quotes for natural language messages, string interpolations, and whenever you know there will be single quotes within the string.

Here are a couple of examples:

name = 'Bob' # Natural language print("It is easy to get confused with single and double quotes in Python.") # String interpolation print(f"{name} said there will be food.") # No need to escape a character print("We're going skiing this winter.") # Quotation inside a string print("My favorite quote from Die Hard is 'Welcome to the party, pal'")

As you can see, we can easily embed quotations into strings surrounded by double quotation marks. Also, there's no need to escape a character as we had to with single quotes.

**Keep in mind**: you can't use double quotes again in a string surrounded by double quotes. Doing so will result in the same syntax error as with single quotes:

print("You can't use "double quotes" inside this string.")

To mitigate, you can reuse the solution from the previous section, but you can also wrap the string in single quotes instead:

print('You can use "double quotes" like this.')

Now you know how to use both single and double quotes in Python. We'll recap on the differences and introduce best practices next.

Here's a summary table answering the question *Should you use single or double quotes in Python*:

In short, you can use both in all cases, but double quotes are more often used with text and longer strings. There's no one forbidding you to use single quotes everywhere, but you'll have to be more careful, as single quotes are more sensitive to specific characters.

There are some official recommendations from the creators of Python, so let's go over them next.

According to PEP8:

- PEP doesn't make a recommendation on whether to use single or double quotes – pick a rule and stick to it.
- When a string is surrounded with single quotes, use double quotes inside it to avoid backslashes.
- When a string is surrounded with double quotes, use single quotes inside it to avoid backslashes.
- When using triple quoted strings, always use double quote characters inside it.

We'll go over triple quoted strings and their use cases shortly.

Best practices for single quoted strings:

- Make sure the string is somewhat short, or you're dealing with a string literals
- Make sure there are no single quotations inside the string, as adding escape characters has a toll on readability.

Best practices for double quoted strings:

- Use double quotes for text and string interpolation.
- Use double quotes when there's a quotation inside a string – you can easily surround the quotation with single quotes.

The ultimate answer is – it **depends**, mostly on your style preferences. Python doesn't make any difference between single and double quotes, so the decision is up to you.

What you shouldn't do is constantly switch between single and double quotes inside a single Python file or a module. Pick the one you like better and be consistent with it.

Yep – there's even a third type of quote in Python. These have their own set of advantages:

- You can use both single and double quotes inside them.
- You can split the string into multiple lines.
- They are considered as a best practice when writing docstrings.

Let's go over a couple of examples:

print("""Triple quote string example 1""") print('''Triple quote string example 2''') print("""Here's a string I'll split into mulitple lines.""") print("""You can use 'single quotes' and "double quotes" inside!""")

As you can see, there's no dedicated triple quote character on a keyboard, so we write them using either three single or three double quotes. The biggest advantage is that you can split the string into multiple lines just by pressing *Enter*, which radically improves the readability.

Still, a primary use case for triple quotes are documentation strings (docstrings) for functions:

def sum_list(lst: list): """Iterates over every list element and sums them. Keyword arguments: lst -- the input sequence of numbers. """ res = 0 for num in lst: res += num return res

You're free to use both `'''`

and `"""`

to surround a docstring, but the convention is to use the latter.

Long story short – the differences between single and double quoted strings in Python are minimal. You can use either one for anything – just make sure to stick to your programming conventions. There are some use cases when one type has the edge over the other, but these are few and far between.

Single quoted strings could cause you some trouble if there are quotations inside the string, so keep that in mind. Double quoted strings are a safer bet, but not enough to pick one over the other.

- Python If-Else Statement in One Line – Ternary Operator Explained
- Python Structural Pattern Matching – Top 3 Use Cases to Get You Started
- Dask Delayed – How to Parallelize Your Python Code With Ease

- Sign up for my newsletter
- Subscribe on YouTube
- Connect on LinkedIn

To **leave a comment** for the author, please follow the link and comment on their blog: ** Python - Better Data Science**.

Want to share your content on python-bloggers? click here.

The post Matrix Addition Explained (with Python examples) appeared first on PyShark. The post Matrix Addition Explained (with Python examples) first appeared on Python-bloggers.]]>

Want to share your content on python-bloggers? click here.

In this article we will discuss the steps and intuition for matrix addition with examples using Python.

**Table of contents**

In this article we explain the intuition and steps of matrix addition.

The examples used are fairly simple and don’t require even a calculator. However, the approaches learnt in this article can be applied on more complex matrix additions.

We also explore how quick and easy it is to perform matrix addition using Python.

To continue following this tutorial we will need the following Python library: numpy.

pip install numpy

Two matrices can be added if and only if they have the same dimension (both are 2×2, 3×3, and so on).

For an intuitive example let’s consider 2 farmers who both have some apples and some grapes in storage. We can represent this as a table:

Storage |
Farmer 1 | Farmer 2 |

Apples | 3 | 2 |

Grapes | 7 | 5 |

which can also be simply shown in a matrix:

$$A = \begin{bmatrix} 3 & 2 \\ 7 & 5 \end{bmatrix}$$

These two farmers have collected some more fruit and are carrying it back to storage. The amount of fruit they collected can also be represented as a table:

Carrying |
Farmer 1 | Farmer 2 |

Apples | 1 | 3 |

Grapes | 2 | 2 |

which can also be simply shown in a matrix:

$$B = \begin{bmatrix} 1 & 3 \\ 2 & 2 \end{bmatrix}$$

Once brought to the storage, they calculate how much the new total number of fruit in the storage is. And they do it by just adding the fruit number together to get:

Total |
Farmer 1 | Farmer 2 |

Apples | 4 | 5 |

Grapes | 9 | 7 |

Farmer 1 added apples to apples (3+1=4) and grapes to grapes (7+2=9). Farmer 2 did the same thing, and got 5 (2+3) and 7 (5+2) respectively.

Now let’s do the same thing in matrix form:

$$C = A + B = \begin{bmatrix} 3 & 2 \\ 7 & 5 \end{bmatrix} + \begin{bmatrix} 1 & 3 \\ 2 & 2 \end{bmatrix} = \begin{bmatrix} 3+1 & 2+3 \\ 7+2 & 5+2 \end{bmatrix} = \begin{bmatrix} 4 & 5 \\ 9 & 7 \end{bmatrix}$$

And we see that matrix \(C\) has the same values as the table with totals above it.

We can further generalize this approach for a \(m \times n\) dimension matrix:

$$A + B = \begin{bmatrix} a_{11} & a_{12} & \dots & a_{1n} \\ a_{21} & a_{22} & \dots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1} & a_{m2} & \dots & a_{mn} \end{bmatrix} + \begin{bmatrix} b_{11} & b_{12} & \dots & b_{1n} \\ b_{21} & b_{22} & \dots & b_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ b_{m1} & b_{m2} & \dots & b_{mn} \end{bmatrix} = \\[50pt] = \begin{bmatrix} a_{11}+ b_{11} & a_{12}+b_{12} & \dots & a_{1n}+b_{1n} \\ a_{21}+b_{21} & a_{22}+b_{22} & \dots & a_{2n}+b_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1}+b_{m1} & a_{m2}+b_{m2} & \dots & a_{mn}+b_{mn} \end{bmatrix} $$

In order to perform the matrix vector multiplication in Python we will use the numpy library. And the first step will be to import it:

import numpy as np

Numpy has a lot of useful functions, and for this operation we will use the add() function which adds arrays element-wise.

Recall that in Python matrices are constructed as arrays, and that matrices need to be of the same dimension to be added. And the next step will be to define the input matrices.

We are going to use the same 2×2 matrices as in the previous section:

A = np.array([[3, 2], [7, 5]]) B = np.array([[1, 3], [2, 2]])

Now that we have the required matrices, we can easily calculate the matrix resulting from the matrix addition:

C = np.add(A, B) print(C)

And you should get:

[[4 5] [9 7]]

which is exactly the same output as in our example where we calculated it manually.

In this article we discussed the intuition behind matrix by vector and matrix by matrix multiplication using both linear algebra and graphic approaches, as well as shown complete examples using Python.

The post Matrix Addition Explained (with Python examples) appeared first on PyShark.

To **leave a comment** for the author, please follow the link and comment on their blog: ** PyShark**.

Want to share your content on python-bloggers? click here.

Want to share your content on python-bloggers? click here.

Here is a link to a dashboard illustrating bivariate time series forecasting with the package ahead:

https://thierry.shinyapps.io/ridge2shiny/

This dashboard is more specifically about `ahead::ridge2f`

(in R) and `ahead.Ridge2Regressor`

(in Python) **hyperparameters’ meaning and impact**. In the first two rows of the figure, everything related to `ahead::ridge2f`

and `ahead.Ridge2Regressor`

is colored in blue, in-sample and out-of-sample, whereas input series’ observed values are colored in red. Here are **a few things you could try**:

**Illustrating**Leave every other parameter constant – to their default value. Set the number of lags to 3, and increase the number of nodes in the hidden layer*overfitting*:`nb_hidden`

. Observe what happens on the right (two first rows of the figure), when the input is perfectly fitted.**Illustrating**Leave every other parameter constant – to their default value. Increase \(\lambda_1\), and observe the regression coefficients (third row of the figure) associated to the original features \(x_1, x_2, \ldots\) being shrinked towards zero.*shrinkage*:**Illustrating**Leave every other parameter constant – to their default value. Increase \(\lambda_2\), and observe the regression coefficients (third row of the figure) associated to the hidden layer \(h_1, h_2, \ldots\) being shrinked towards zero.*shrinkage*2:

To **leave a comment** for the author, please follow the link and comment on their blog: ** T. Moudiki's Webpage - Python**.

Want to share your content on python-bloggers? click here.

The post Create Identity Matrix using Python appeared first on PyShark. The post Create Identity Matrix using Python first appeared on Python-bloggers.]]>

Want to share your content on python-bloggers? click here.

In this article we will discuss the steps and intuition for creating the identity matrix and show examples using Python.

**Table of contents**

- Introduction
- Identity matrix explained
- Identity matrix properties
- Identity matrix in Python
- Conclusion

The identity matrix (\(I\)) is often seen in a lot of matrix expressions in linear algebra.

At this point you should be familiar with what a matrix represents as it will be useful to understand the meaning behind the identity matrix.

To continue following this tutorial we will need the following Python library: numpy.

pip install numpy

We already know what a matrix is, but what exactly is an identity matrix and how is it being used?

The identity matrix \(I_n\) is a square matrix of order \(n\) filled with ones on the main diagonal and zeros everywhere else.

Here are a few examples:

$$I_1 = \begin{bmatrix} 1 \end{bmatrix}$$

$$I_2 = \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}$$

$$I_3 = \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{bmatrix}$$

and so on for the larger dimensions.

Graphically, the \(I_2\) matrix simply represents the base vectors:

$$\vec{i}_1 = (0, 1)$$

$$\vec{i}_2 = (1, 0)$$

Here are some useful properties of an identity matrix:

- An identity matrix is always a square matrix (same number of rows and columns), such as: 2×2, 3×3, and so on.
- The result of multiplying any matrix by an identity matrix is the matrix itself (if multiplication is defined)

$$A \times I = A$$

$$\begin{bmatrix} 3 & 7 \\ 2 & 5 \end{bmatrix} \times \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} = \begin{bmatrix} 3 & 7 \\ 2 & 5 \end{bmatrix}$$ - The result of multiply a matrix by its inverse matrix is the identity matrix

$$A \times A^{-1} = I$$

$$\begin{bmatrix} 3 & 7 \\ 2 & 5 \end{bmatrix} \times \begin{bmatrix} 5 & -7 \\ -2 & 3 \end{bmatrix} = \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}$$

In order to create an identity matrix in Python we will use the numpy library. And the first step will be to import it:

import numpy as np

Numpy has a lot of useful functions, and for this operation we will use the identity() function which creates a square array filled with ones in the main diagonal and zeros everywhere else.

Now let’s create a 2×2 identity matrix:

I = np.identity(2) print(I)

And you should get:

[[1. 0.] [0. 1.]]

Now you know how to create an identity matrix and can further explore matrix operations by calculating matrix inverses and multiplying matrices in Python.

In this article we discussed the steps and intuition for creating the identity matrix, as well as shown a complete example using Python.

The post Create Identity Matrix using Python appeared first on PyShark.

To **leave a comment** for the author, please follow the link and comment on their blog: ** PyShark**.

Want to share your content on python-bloggers? click here.