Read More “How to Make a Countplot in Seaborn” »

The post How to Make a Countplot in Seaborn appeared first on Pythoneo.

]]>The full seaborn.countplot consist of several parameters:

(*, x=None, y=None, hue=None, data=None,

order=None, hue_order=None, orient=None,

color=None, palette=None, saturation=0.75,

dodge=True, ax=None, **kwargs)

I will share my knowledge to explain to you you parameters of the countplot Seaborn method. It will help you to create a move advanced Seaborn countplot.

This is the completed code to create a counterplot in Python using the Seaborn module.

import seaborn as sns import matplotlib.pyplot as plt df = sns.load_dataset('taxis') sns.countplot(x='passengers', data=df) plt.show()

To flip the chart, just change the x argument to y.

sns.countplot(y='passengers', data=df)

You can also use a orient parameter and set “v” for a vertical alignment or “h” for a horizontal one.

To increase the amount of data in the chart you may use the hue parameter. It is adding an additional sets of data to your counterplot graph. I decided to visualize payments with color of the taxi to check the relationship between them.

sns.countplot(x='payment', data=df, hue='color')

The hue_order parameter gives you the possibility of changing the order of a hue. I used simply df[‘color’].value_counts().index[::-1] structure to change the order by index in the reverse order.

sns.countplot(x='payment', data=df, hue='color', hue_order = df['color'].value_counts().index[::-1])

To sort the data series use the order parameter. I picked df[‘passengers’].value_counts().index to sort counts.

sns.countplot(x='passengers', data=df, order=df['passengers'].value_counts().index)

To sort the data series in ascending order, add the reverse indexing using index[::-1].

sns.countplot(x='passengers', data=df, order=df['passengers'].value_counts().index[::-1])

It is also possible to change the color of your python countplot. I set the color parameter to blue.

sns.countplot(x='passengers', data=df, color='blue')

If one color is not enough for you or you want to make your chart look more attractive, use the palette parameter. I dediced to use the inferno.

sns.countplot(x='passengers', data=df, palette='inferno')

For those who care about details, you can also change the color saturation. The default is 0.75. Watch the saturation change as you lower it to 0.2.

sns.countplot(x='passengers', data=df, saturation=0.2)

To stack data in a countplot, use a dodge. By default, dodge is set to true. If you change this parameter to false, the count graph will change like this. The data has been accumulated.

sns.countplot(x='payment', data=df, hue='color', dodge=False)

These are all the parameters of the countplot method that I wanted to discuss for you. I hope you will improve your charting skills at Seaborn with this python course.

The post How to Make a Countplot in Seaborn appeared first on Pythoneo.

]]>The post AttributeError: partially initialized module ‘cv2’ has no attribute ‘img’ (most likely due to a circular import) appeared first on Pythoneo.

]]>There are a few reason on how you may meet such a problem.

First of all it is not only “AttributeError: partially initialized module ‘cv2’ has no attribute ‘img’ (most likely due to a circular import)” issue. I mean it doesn’t have to be ‘img’ which is problematic. You may get “AttributeError: module ‘cv2’ has no attribute ‘imread'” or similar once.

Strat from the easiest way which is to reinstall cv2 module. To do that you need to run

pip uninstall opencv-python pip uninstall opencv-contrib-python pip install opencv-contrib-python pip install opencv-python

If this will not help you need to remove problematic file.

Go to to your project. For me it is C:\Users\pythoneo\PycharmProjects\Project1\venv\Lib\site-packages\cv2.

In this directory find cv2.pyd file and remove it.

Run the same commands again.

pip uninstall opencv-python pip uninstall opencv-contrib-python pip install opencv-contrib-python pip install opencv-python

This helped me so I believe it will help you as well.

The post AttributeError: partially initialized module ‘cv2’ has no attribute ‘img’ (most likely due to a circular import) appeared first on Pythoneo.

]]>Read More “How to enumerate dictionary in Python?” »

The post How to enumerate dictionary in Python? appeared first on Pythoneo.

]]>Let’s say this is my dictionary:

my_dictionary = {'Audi' : 1000, 'BMW' : 2000, 'Mercedes' : 3000}

This is how to enumerate the dictionary in Python:

my_dictionary = {'Audi' : 1000, 'BMW' : 2000, 'Mercedes' : 3000} for i, (car, number) in enumerate(my_dictionary.items()): print("index: {}, car: {}, number: {}".format(i, car, number))

Enumerate is returning the tuple object and my_dictionary.items returns an iterator. To gether they are returning both an index and a tuple of a pair key and value.

The post How to enumerate dictionary in Python? appeared first on Pythoneo.

]]>Read More “How to compare two arrays in Numpy?” »

The post How to compare two arrays in Numpy? appeared first on Pythoneo.

]]>Let’s start from the easiest example.

The most convenient way to compare two Numpy arrays is to use Numpy array_equal method which simply takes two arrays as parameters.

import numpy as np my_array = np.array([1, 2, 3, 4]) my_array_to_compare = np.array([1, 2, 3, 4]) print(f'Are they the same? {np.array_equal(my_array, my_array_to_compare)}') my_array = np.array([1, 2, 3, 4]) my_array_to_compare = np.array([1, 2, 3, 4, 5]) print(f'Are they the same? {np.array_equal(my_array, my_array_to_compare)}')

Alternatively you can also use another Numpy method which is array_equiv.

my_array = np.array([1, 2, 3, 4]) my_array_to_compare = np.array([1, 2, 3, 4]) print(f'Are they the same? {np.array_equiv(my_array, my_array_to_compare)}') my_array = np.array([1, 2, 3, 4]) my_array_to_compare = np.array([1, 2, 3, 4, 5]) print(f'Are they the same? {np.array_equiv(my_array, my_array_to_compare)}')

This how to compare the arrays when you would like to know if they are equal.

In another type of use cases you may like to know only when arrays are not equal.

import numpy as np my_array = np.array([1, 2, 3, 4]) my_array_to_compare = np.array([1, 2, 3, 4]) np.testing.assert_array_equal(my_array, my_array_to_compare)

When arrays are the same this will report nothing.

import numpy as np my_array = np.array([1, 2, 3, 4]) my_array_to_compare = np.array([1, 2, 3, 4, 5]) np.testing.assert_array_equal(my_array, my_array_to_compare)

The arrays are different so this will report an error.

Of course you can handle this expection to get more meaningful info.

Similarly to assert_array_equal you can use assert_allclose Numpy method.

import numpy as np my_array = np.array([1, 2, 3, 4]) my_array_to_compare = np.array([1, 2, 3, 4]) np.testing.assert_allclose(my_array, my_array_to_compare) my_array = np.array([1, 2, 3, 4]) my_array_to_compare = np.array([1, 2, 3, 4, 5]) np.testing.assert_allclose(my_array, my_array_to_compare)

And this is the output you may need to expect from assert_allclose.

You can all confirm that two arrays are the same using all or any methonds.

import numpy as np my_array = np.array([1, 2, 3, 4]) my_array_to_compare = np.array([1, 2, 3, 4]) if_the_same = (my_array == my_array_to_compare).any() print(f'Are they the same? {if_the_same}') my_array = np.array([1, 2, 3, 4]) my_array_to_compare = np.array([1, 2, 3, 4]) if_the_same = (my_array == my_array_to_compare).all() print(f'Are they the same? {if_the_same}')

As you can see you need to define an additional variable and call all or any methods to get a result.

The post How to compare two arrays in Numpy? appeared first on Pythoneo.

]]>Read More “How to square a matrix in Numpy?” »

The post How to square a matrix in Numpy? appeared first on Pythoneo.

]]>The easiest way and the most convenient one is just to use a built-in function of Numpy square. It just take my array as an argument and squares it.

import numpy as np my_array = np.array([1, 2, 3, 4]) squared_array = np.square(my_array) print(f"My array is equal to {my_array}") print(f"Squared array is equal to {squared_array}")

As an output you can see that my array got squared as expected.

You can also use power Numpy method. Square is the same as second power so it will work the same.

import numpy as np my_array = np.array([1, 2, 3, 4]) squared_array = np.power(my_array, 2) print(f"My array is equal to {my_array}") print(f"Squared array is equal to {squared_array}")

The most pythonic way would be to use ** 2 which also square my array.

import numpy as np my_array = np.array([1, 2, 3, 4]) squared_array = my_array ** 2 print(f"My array is equal to {my_array}") print(f"Squared array is equal to {squared_array}")

These are 3 different ways to square a matrix using Numpy. Of course Numpy square function is the most efficient one for a comercial purpose.

The post How to square a matrix in Numpy? appeared first on Pythoneo.

]]>Read More “Exploding out slices of a Pie Chart in Plotly” »

The post Exploding out slices of a Pie Chart in Plotly appeared first on Pythoneo.

]]>To see how to explode slice out I need example pie chart. I imported Plotly Express and use tips data which is defined in Plotly as example data set to work on.

This is a code of my example pie chart.

import plotly.express as px data_frame = px.data.tips() pie_chart = px.pie(data_frame, names='day', values='tip', title='Tips values by day', template='gridon') pie_chart.show()

To explode out slices of my pie chart I need to update traces and define pull parameter. The higher the pull the more slices are exploded out from the pie chart.

pie_chart.update_traces(pull=0.1)

There is also a possibility to explode only one slice of a pie. To explode only one of them you need to create a list of pull parameter.

pie_chart.update_traces(pull=[0.1, 0, 0, 0])

And this is how one exploded out slice look like. Thanks to that I impored visibility of Sundays tips.

See also: Exploding out slices of a Pie Chart in Excel

The post Exploding out slices of a Pie Chart in Plotly appeared first on Pythoneo.

]]>Read More “How to uninstall Numpy?” »

The post How to uninstall Numpy? appeared first on Pythoneo.

]]>To uninstall Numpy package you need just this one command to run:

pip3 uninstall numpy

After typing y the Numpy package got uninstalled.

Another possibility is to uninstall Numpy directly from the tool you are using. I’m using PyCharm.

To uninstall Numpy in PyCharm click File -> Settings -> Python Interpreter.

Choose Numpy from the list and click Minus sign as you can see in the picture below.

Numpy will be uninstalled.

You need to unistall Numpy the same way you installed that. I show you how to unistall Numpy package using pip3.

Another methods you may use to unistall Numpy succesfuly:

yum remove python3-numpy

apt-get remove python-numpy

pip uninstall numpy

Remember you need to be root to be able to uninstall Numpy. If you are not the root and you got the error related to permission you need to put sudo or log as root.

pip3 uninstall numpy

The post How to uninstall Numpy? appeared first on Pythoneo.

]]>Read More “How to create Seaborn Heatmap?” »

The post How to create Seaborn Heatmap? appeared first on Pythoneo.

]]>You may need heatmap chart when you want to see fluctuations of two categories. Heatmap are useful for visualisation of two-dimentional data.

To create a heatmap you will need to import Python modules like: Seaborn, Matplotlib, Numpy and Pandas. It depends on your setup and the source of your data. I am going to generate the data so I don’t need Pandas which would be useful when you are taking the data from external source like csv file.

import numpy as np import seaborn as sns import matplotlib.pyplot as plt

This is how I’m generating the data.

my_random_data = np.random.rand(4, 4)

It’s just to have data to work with.

I’m going to define the data sets to show in the heatmap, create subplots and set the size of the chart.

f, ax = plt.subplots(figsize=(9, 6))

Let’s jump to the core heatmap definition.

ax = sns.heatmap(my_random_data, annot = True, cmap = 'coolwarm', linecolor = 'black', linewidths = 2, robust = True)

I’m going to save my heatmap as a png picture.

f.savefig('My heatmap.png')

To see the heatmap I need Matplotlib show method. This is not mandatory as I’ve already saved my Seaborn heatmap as a png picture.

plt.show()

My Seaborn heatmap is almost ready. It requires just some polishing. I need to name my chart and labels to improve the visibility.

ax.set_title('Heatmap by Pythoneo.com') ax.set_xlabel('My X label') ax.set_ylabel('My Y label')

The heatmap is ready.

That’s the full code:

import numpy as np import seaborn as sns import matplotlib.pyplot as plt my_random_data = np.random.rand(4, 4) f, ax = plt.subplots(figsize=(9, 6)) ax = sns.heatmap(my_random_data, annot = True, cmap = 'coolwarm', linecolor = 'black', linewidths = 2, robust = True) ax.set_title('Heatmap by Pythoneo.com') ax.set_xlabel('My X label') ax.set_ylabel('My Y label') f.savefig('My heatmap.png') plt.show()

The post How to create Seaborn Heatmap? appeared first on Pythoneo.

]]>Read More “How to create a BarPlot in SeaBorn?” »

The post How to create a BarPlot in SeaBorn? appeared first on Pythoneo.

]]>I have prepared csv file with registration vehicles data.

Let’s see the details using Pandas Python library.

import pandas as pd cars = pd.read_csv('vehicles.csv') print(cars)

I’d like to create a barplot chart which contains the data about the number of registered vehicles.

I need to see Body_Type and No_Of_Vehicles.

To create a basic SeaBorn BarPlot I need to import Pandas, Seaborn and Matplotlib Python libraries. To insert a barplot I am using seaborn.barplot method. As x and y I’m taking the columns I need. And data is my data source which I defined. Plt.show function will help to display the chart.

import pandas as pd import matplotlib.pyplot as plt import seaborn as sn cars = pd.read_csv('vehicles.csv') sn.barplot(x = 'Body_Type', y = 'No_Of_Vehicles', data = cars) plt.show()

The post How to create a BarPlot in SeaBorn? appeared first on Pythoneo.

]]>Read More “What is the use of assert in Python?” »

The post What is the use of assert in Python? appeared first on Pythoneo.

]]>Do you know what is the difference between a Python professional and a beginner?

The Python code of an experienced Python developer takes care of the correctness of the data.

Let’s see how to use assert for a simple data validation check.

I’ve used assert to take care of the data to be validated. In my case, I’m confident that the delivery date will not be earlier than the order date. I used assert to take care of the date validation check.

import datetime as dt order_date = dt.date(2022, 1, 1) delivery_date = dt.date(2022, 1, 1) assert order_date <= delivery_date, 'Delivery date can\'t be earlier than order date'

Even when both dates are the same (technically it is possible to order and deliver on the same date), nothing will happen. After you run the code in such a way that literally nothing will happen. It means that the code can move on because assert will not find the problem here.

And what will happen when assert finds a date validation error?

import datetime as dtorder_date = dt.date(2022, 6, 1)

delivery_date = dt.date(2022, 1, 1)

assert order_date <= delivery_date, 'Delivery date can\'t be earlier than order date'

Assert properly checked that the delivery date is earlier than the order date, which we agreed is not proper. That's how assert saved us from a wrong date being provided. Thanks to assert, we checked that our code was working wrongly.

This is how the use of assert found a bug in my Python code.

The post What is the use of assert in Python? appeared first on Pythoneo.

]]>