Read More “How to use curdoc in Bokeh” »

The post How to use curdoc in Bokeh appeared first on Pythoneo.

]]>Here’s an example of how you can use curdoc() to add a plot to a Bokeh document:

from bokeh.plotting import figure from bokeh.io import show, output_notebook from bokeh.models import ColumnDataSource from bokeh.layouts import row from bokeh.palettes import Spectral4 from bokeh.sampledata.stocks import AAPL # Prepare the data df = AAPL source = ColumnDataSource(df) # Create a line plot p = figure(x_axis_type="datetime", title="AAPL Stock Price") p.line(x="date", y="close", line_width=2, source=source, legend_label="Close") # Add the plot to the current document curdoc().add_root(row(p)) # Show the plot show(p)

In this example, we first import the required modules from Bokeh, including the figure, show, output_notebook, ColumnDataSource, row, Spectral4, and AAPL sample data.

Then we prepare the data by converting the AAPL sample data into a ColumnDataSource and create a line plot using the figure method.

Finally, we use the add_root method of the curdoc() object to add the plot to the current document, and we show the plot using the show function.

The post How to use curdoc in Bokeh appeared first on Pythoneo.

]]>Read More “How to solve TypeError: ‘set’ object is not subscriptable” »

The post How to solve TypeError: ‘set’ object is not subscriptable appeared first on Pythoneo.

]]>I encountered a type error in Python, which I dealt with. So I want to show you how to do it when you also get a type error of ‘set’ object is not subscriptable.

I have a defined set.

my_set = {'New York', 'Austin', 'Chicago'}

I’m sure that my set contains the value I need.

The output of the below line is True.

print('New York' in my_set)

I wanted to access the value by index.

print(my_set[0])

I’m not able to access it by index because it throws me an error “object is not subscriptable”.

Traceback (most recent call last): File "C:\Users\Pythoneo\PycharmProjects\new.py", line 5, inprint(my_set[0]) TypeError: 'set' object is not subscriptable Process finished with exit code 1

The error occurs because, by definition, the set data type contains data that is not sorted. For this reason, indexing (as well as slicing) does not work for the set data type.

If you can’t access a value from a set data type, then use a different data type. In my case I changed set to list. In fact, the change in the code is changing the curly brackets to square brackets.

If you don’t want to use a list, you can change the data type to tuple or dictionary.

The post How to solve TypeError: ‘set’ object is not subscriptable appeared first on Pythoneo.

]]>Read More “How to calculate the factorial of an array in Numpy?” »

The post How to calculate the factorial of an array in Numpy? appeared first on Pythoneo.

]]>In Numpy, it is very easy to calculate the factorial. Just use the factorial method.

import numpy as np my_number = 7 print(f"The factorial of {my_number} is {np.math.factorial(my_number)}.")

Output:

The factorial of 7 is 5040.

Calculating the factorial for the given number is simple. However, this method will not work for the array factorial.

import numpy as np my_array = np.array([[1,2,3],[4,5,6]]) print(f"The factorial of my array is {np.math.factorial(my_array)}.")

You will get the following error:

Traceback (most recent call last): File "C:\Users\pythoneo\PycharmProjects\venv\myfile.py", line 5, inprint(f"The factorial of my array is {np.math.factorial(my_array)}.") TypeError: only integer scalar arrays can be converted to a scalar index Process finished with exit code 1

You need another way to calculate the factorial of a array.

The scipy module will help you to calculate the factorial of the array. It includes a function that will calculate the factorial also for the Numpy array.

import numpy as np import scipy.special my_array = np.array([[1,2,3],[4,5,6]]) my_factorial = scipy.special.factorial(my_array) print(f"The factorial of my array is \n{my_factorial}")

Output:

The factorial of my array is [[ 1. 2. 6.] [ 24. 120. 720.]]

The post How to calculate the factorial of an array in Numpy? appeared first on Pythoneo.

]]>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.

]]>