Read More “How to convert list to Numpy array?” »

The post How to convert list to Numpy array? appeared first on Pythoneo.

]]>There are 3 different ways to convert Python list to Numpy array.

How to convert list to Numpy array using array method?

The easiest way to cast list to array is to use array method and set list as a single parameter.

import numpy as np my_list = [1, 2, 3, 4, 5, 6] my_array = np.array(my_list) print(f"Numpy array converted " f"from Python list: {my_list}")

How to convert list to Numpy array using asarray method?

The other way to cast list to array is to use asarray method and also set list as a single parameter.

import numpy as np my_list = [1, 2, 3, 4, 5, 6] my_array = np.asarray(my_list) print(f"Numpy array converted " f"from Python list: {my_list}")

How to convert list of lists to Numpy array using concatenate method?

Let’s check more difficult task.

To convert list of lists to Numpy array you need to use Python concatenate method. The parameter you need to use to cast it properly is axis=0.

import numpy as np my_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] my_array = np.concatenate(my_list, axis=0) print(f"Numpy array converted " f"from Python list of lists: {my_list}")

The post How to convert list to Numpy array? appeared first on Pythoneo.

]]>Read More “How to create bar chart in matplotlib?” »

The post How to create bar chart in matplotlib? appeared first on Pythoneo.

]]>To create a bar chart in MatPlotlib I need data. I have a list of salesman and number of product_sold.

There is a bar function which creates a bar chart. As arguments I have salesmman as x values, product_sold for y values and more optionals. I used lightgray as color theme and brown for edge colors (ec stands for edge color).

import matplotlib.pyplot as plt products_sold = [55, 72, 63, 47, 58] salesman = ['Joe', 'Monica', 'Tom', 'Ana', 'Paul'] plt.bar(salesman, products_sold, color='lightgray',ec='brown') plt.title('Python course sales') plt.show()

This is how my bar grapg looks like. I can improve it even further using more bar function arguments.

The post How to create bar chart in matplotlib? appeared first on Pythoneo.

]]>Read More “How to calculate determinant of matrix?” »

The post How to calculate determinant of matrix? appeared first on Pythoneo.

]]>To calculate determinant you need to use linear algebra. It offers a dedicated det function thanks to which it is very easy to calculate a determinant.

import numpy as np my_matrix = np.array([(10, 2), (7, 8)]) determinant = np.linalg.det(my_matrix) print(f"Determinant equals {round(determinant, 2)}")

I created my an example matrix a called it my_matrix. Then I used np.linalg.det function which takes my_matrix as an argument.

Finally I printed out the result which I rounded to the two decimal places. I recommend roundind results. Otherwise the result will be more like 65.99999999999997. The reason is that Numpy is calculating numerically and not analytically. That’s why the results which are not rounded up looks very strange and they are not very useful.

Sometimes it may happen that you will get a error like:

raise LinAlgError('%d-dimensional array given. Array must be ' numpy.linalg.LinAlgError: 1-dimensional array given. Array must be at least two-dimensional

That kind of errors tells you that it is something wrong with you matrix. Please check if the tuples are equal. Maybe some of them contains obsolete values?

The other type of errors is like below one:

r = _umath_linalg.det(a, signature=signature) TypeError: No loop matching the specified signature and casting was found for ufunc det

This one is not so obvious because it does not tell much. The reason of the error is that the data type of matrix values is not the same. Probably one of them is a string. The data type of values in the matrix must be the same.

I hope you find this tutorial useful and you are able to calculate determinant in Numpy as a pro.

The post How to calculate determinant of matrix? appeared first on Pythoneo.

]]>Read More “How to insert Pie Chart in Matplotlib?” »

The post How to insert Pie Chart in Matplotlib? appeared first on Pythoneo.

]]>To insert the chart we need to prepare data to be visualized.

import matplotlib.pyplot as plt products_sold = [55, 72, 63, 47, 58] salesman = ['Joe', 'Monica', 'Tom', 'Ana', 'Paul']

I imported matplotlib and prepared a list of salesman and products they sold.

To create a pie chart I need to use pie function and use products_sold as an argument

import matplotlib.pyplot as plt products_sold = [55, 72, 63, 47, 58] salesman = ['Joe', 'Monica', 'Tom', 'Ana', 'Paul'] plt.pie(products_sold) plt.show()

This is the first version of pie chart.

I like it but it needs a few improvements because it is not very useful.

Let’s start from adding a title with title function.

import matplotlib.pyplot as plt products_sold = [55, 72, 63, 47, 58] salesman = ['Joe', 'Monica', 'Tom', 'Ana', 'Paul'] plt.pie(products_sold) plt.title('Python course sales') plt.show()

Title is here. Now let’s add labels.

To add labels I added labels as an additional parameter to pie function. I set salesman as a list of labels.

import matplotlib.pyplot as plt products_sold = [55, 72, 63, 47, 58] salesman = ['Joe', 'Monica', 'Tom', 'Ana', 'Paul'] plt.pie(products_sold, labels=salesman) plt.title('Python course sales') plt.show()

It is getting better. Now at least I know what is this pie chart about.

Next thing I need are values.

To add values I used autopct argument. To define the format of my values I used %.0f%%’ because I can see digits without decimals (0 decimals).

import matplotlib.pyplot as plt products_sold = [55, 72, 63, 47, 58] salesman = ['Joe', 'Monica', 'Tom', 'Ana', 'Paul'] plt.pie(products_sold, labels=salesman, autopct='%.0f%%') plt.title('Python course sales') plt.show()

With autopercentage I can see the first basic version of pie chart I can see.

Still it is not enough for me. I’d like explode the sales of Monica. To explode a slice of pie chart in Matplotlib I need to define explode list first. 0.2 is how much it needs to be exploded. Then I added explod parameter to pie function.

import matplotlib.pyplot as plt products_sold = [55, 72, 63, 47, 58] salesman = ['Joe', 'Monica', 'Tom', 'Ana', 'Paul'] explode = [0, 0.2, 0, 0, 0] plt.pie(products_sold, labels=salesman, autopct='%.0f%%', explode=explode) plt.title('Python course sales') plt.show()

A slice is exploded out now.

I’m still not very please with the chart. Exploded slice is too close to the chart’s title. I’d like to move the chart a bit counterclockwise. Adding startangle parameter with value of 20 does the job.

import matplotlib.pyplot as plt products_sold = [55, 72, 63, 47, 58] salesman = ['Joe', 'Monica', 'Tom', 'Ana', 'Paul'] explode = [0, 0.2, 0, 0, 0] plt.pie(products_sold, labels=salesman, autopct='%.0f%%', explode=explode, startangle=20) plt.title('Python course sales') plt.show()

This is much better! What can I do to make it more beutiful?

I’d like to see it more 3D. To do it I need just to enable shadow effect.

import matplotlib.pyplot as plt products_sold = [55, 72, 63, 47, 58] salesman = ['Joe', 'Monica', 'Tom', 'Ana', 'Paul'] explode = [0, 0.2, 0, 0, 0] plt.pie(products_sold, labels=salesman, autopct='%.0f%%', explode=explode, startangle=20, shadow=True) plt.title('Python course sales') plt.show()

If you’d like to enlarge your pie chart you can also do it easily. Radius parameter is responsible for pie chart size. By deafault it is 1. To increase the size by 10% just use 1.1 like that.

Also adding edge color would look nice. I’d like to see black. To do it you need to use wedgeprops parameter.

import matplotlib.pyplot as plt products_sold = [55, 72, 63, 47, 58] salesman = ['Joe', 'Monica', 'Tom', 'Ana', 'Paul'] explode = [0, 0.2, 0, 0, 0] plt.pie(products_sold, labels=salesman, autopct='%.0f%%', explode=explode, startangle=20, shadow=True, radius=1.1, wedgeprops={'edgecolor': 'black'}) plt.title('Python course sales') plt.show()

My pie chart is ready. I like it a lot. I hope you do as well.

The post How to insert Pie Chart in Matplotlib? appeared first on Pythoneo.

]]>Read More “How to plot Errorbar using Matplotlib?” »

The post How to plot Errorbar using Matplotlib? appeared first on Pythoneo.

]]>For start I prepare data and insert common plot.

import matplotlib.pyplot as plt x = [0.1, 0.2, 0.3, 0.4, 0.5] y = [1.1, 1.4, 1.7, 1.2, 1.25] plt.plot(x, y) plt.show()

It’s just a common chart. As you can see I have x and y axes populated with values.

Let’s add error. My measurements are not accurate so some errors may occur.

import matplotlib.pyplot as plt x = [0.1, 0.2, 0.3, 0.4, 0.5] y = [1.1, 1.4, 1.7, 1.2, 1.25] error = 0.4 plt.errorbar(x, y, yerr=error, fmt='o', ecolor='red') plt.show()

I have introduced 0.4 of error. This is how much my values may differ.

To plot errorbar I used errorbar method. Also used some arguments:

– x and y are my values as usual

– yerr is my error

– fmt is formatting and I chose ‘o’ to see my marks as o letters (alternatively you may use x)

– ecolor is the color of my error line and I like red for every error

And this is how my errorbar looks like:

Who told errors has to be the same? You can put different ones for every value.

import matplotlib.pyplot as plt x = [0.1, 0.2, 0.3, 0.4, 0.5] y = [1.1, 1.4, 1.7, 1.2, 1.25] error = [0.4, 0.2, 1.1, 0.1, 0.4] plt.errorbar(x, y, yerr=error, fmt='o', ecolor='red') plt.show()

As you can see the error of 0.3 is very high.

Also you may introduce different values of errors for lower and upper ones. Let’s add min and max values of errors like that:

import matplotlib.pyplot as plt x = [0.1, 0.2, 0.3, 0.4, 0.5] y = [1.1, 1.4, 1.7, 1.2, 1.25] min_error = [0.1, 0.15, 0.12, 0.17, 0.11] max_error = [0.4, 0.36, 0.44, 0.19, 0.41] error = [min_error, max_error] plt.errorbar(x, y, yerr=error, fmt='o', ecolor='red') plt.show()

I have specified min errors and max errors and defined them under error.

What if x values are erroneous as well? Then you need to define xerr as well.

import matplotlib.pyplot as plt x = [0.1, 0.2, 0.3, 0.4, 0.5] y = [1.1, 1.4, 1.7, 1.2, 1.25] xerror = 0.02 min_error = [0.1, 0.15, 0.12, 0.17, 0.11] max_error = [0.4, 0.36, 0.44, 0.19, 0.41] error = [min_error, max_error] plt.errorbar(x, y, yerr=error, xerr=xerror, fmt='o', ecolor='red') plt.show()

You may notice that additional error values appeared for x values.

Now you should know how to insert plot errorbar chart using Python Matplotlib library.

The post How to plot Errorbar using Matplotlib? appeared first on Pythoneo.

]]>Read More “How to rotate a matrix?” »

The post How to rotate a matrix? appeared first on Pythoneo.

]]>With Numpy it is very easy to rotate matrix 90 degrees. There is dedicated rot90 Numpy method.

import numpy as np my_array = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]]) print(f"This is my array: \n{my_array}") rotate_array = np.rot90(my_array) print(f"Array rotated: \n{rotate_array}")

To rotate 270 degrees just add 3 as a parameter to rot90 function. This parameter makes 3 rounds of 90 degrees rotation (counter clockwise).

import numpy as np my_array = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]]) print(f"This is my array: \n{my_array}") rotate_array = np.rot90(my_array, 3) print(f"Array rotated 270 degrees: \n{rotate_array}")

This is 270 degrees rotation but we can also say that this is left rotation because this is how to rotate an matrix left direction.

To rotate 180 put np.rot90(my_array, 2). Having np.rot90(my_array, 4) will not change the array at all.

You can also rotate an array over the axes.

import numpy as np my_array = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]]) print(f"This is my array: \n{my_array}") rotate_array = np.rot90(my_array, axes=(1, 0)) print(f"Array rotated over axes=(1, 0): \n{rotate_array}")

I used np.rot90(my_array, axes=(1, 0)) and this is how it got rotated.

The post How to rotate a matrix? appeared first on Pythoneo.

]]>Read More “Count how many zeros you have in array” »

The post Count how many zeros you have in array appeared first on Pythoneo.

]]>For sure you will be surprised. To count a zeros frequency in your matrix you need to use count_nonzero function. Then as a parameter you should use your array == 0. Believe me it works.

import numpy as np my_array = np.array([[1, 0, 5], [5, 3, 0], [0, 0, 2]]) zeros_frequency = np.count_nonzero(my_array == 0) print(f"Count of zeroes in my array: \n{zeros_frequency}")

As you can see count_nonzero function counted zeros.

The post Count how many zeros you have in array appeared first on Pythoneo.

]]>Read More “How to empty an array in Numpy?” »

The post How to empty an array in Numpy? appeared first on Pythoneo.

]]>There are 2 different ways to empty an array in Numpy.

The first method is to use Numpy empty function.

import numpy as np my_array = np.empty(shape=(0, 0)) print(f"My empty array: \n{my_array}")

Empty function created an empty matrix. Thanks to shape parameters you can define a shape of an array. Of course you can change it in the future using reshape function.

Another way is just to create an array but not setting any elements to that. Python allows us to do that.

import numpy as np my_array = np.array([]) print(f"My empty array: \n{my_array}")

The result is exactly the same. Your choise which way you would prefer to choose to create an empty matrix in Numpy.

The post How to empty an array in Numpy? appeared first on Pythoneo.

]]>Read More “How to copy array with Numpy?” »

The post How to copy array with Numpy? appeared first on Pythoneo.

]]>To create a copy of array you just need to use Numpy copy function. As an argument of copy function put your array.

import numpy as np my_array = np.array([1, 3, 5]) print(f"This is my array: \n{my_array}") array_copy = np.copy(my_array) print(f"This is copy of my array: \n{array_copy}")

This is how to create copy. Alternatively you can assign an array to another (array_copy = my_array) or create a view of an array.

The post How to copy array with Numpy? appeared first on Pythoneo.

]]>Read More “How to convert array to binary?” »

The post How to convert array to binary? appeared first on Pythoneo.

]]>Having an array created you can save it as an binary file using tofile setting bin as your file extension.

import numpy as np my_array = np.array([1, 3, 5]) my_binary = my_array.tofile("my_binary.bin")

Python created my_binary.bin file in the default directory. You set your own as you want of course

The post How to convert array to binary? appeared first on Pythoneo.

]]>