One particular element of computer science that has seen a large evolution is the programming language section, which is an integral part of machines and comprises instructions that allow the machines to perform different tasks. Python is one high-level programming language that has immensely grown and is being used in multiple sectors of the industry.
However, Python itself is vast and can be implemented in several different flavors, which shall also be the topic of our discussion in this article, and where we will be looking at the different implementations that currently exist of Python.
We have been using the term “implementation” for a while now. What does this mean? Well, implementation refers to the way the interpreter was written – what languages were used and what is the purpose of that specific interpreter.
Now, let us look at some of the different implementations of Python.
CPython is the default and most widely used interpreter or implementation of Python, written in C. It is the original Python version, which users download from its official website, Python.org. It can be better described as a mixture of both an interpreter and compiler as it converts your written Python source code into bytecode. By bytecode, we refer to a program code that gets compiled and processed into a low-level language that can be used as instructions for the interpreter. It is this bytecode that gets executed on the CPython Virtual Machine.
Since it is the original Python implementation, CPython has the highest compatibility with a variety of Python packages and modules and is the best choice if users need to write code that completely matches the Python standards.
Jython is another Python implementation that has been written in the Java language whose implementation can run in Java platforms. Similar to CPython, it first converts the source code into bytecode, which, as mentioned before, are a set of instructions that are needed by an interpreter. In Jython, these are written in Java and can run on the Java Virtual Machine, which is the same environment that Java itself uses. Jython allows users to easily work with Java programs since you can call, as well as utilize, your Java functions and classes directly from Jython without any additional effort which is immensely beneficial as Python users can get access into the enormous ecosystem of libraries and frameworks that come along with Java. The same is true on the opposite end.
Similar to how Jython has been developed for Java users, IronPython is the popular Python implementation that has been written in C-Sharp (C#) and has been designed to run on the .NET platform. It creates a bridge between the Python and .NET universe and allows Python users to get access to C-sharp functions and classes, as well as .NET libraries and frameworks directly from IronPython. IronPython excels for programs that make use of threading and can be found on the ironpython.net website.
PyPy is the Python implementation that has been written in the Python language itself and is another alternative to CPython. Since it has been created while keeping in mind the specifications of the Python language, it is most compatible with CPython, allowing it to run web frameworks like Django and Flask, and even adds a few improvements on the top of it. PyPy makes use of the concept called Just-in-time (JIT) compilation, which allows it to compile the source code during the execution of the program. This, in turn, has made it several times faster than CPython, in which its runtime speed being slow was a common complaint among users. PyPy completely improves this part of CPython.
Unlike the other implementations of Python mentioned in the list, Cython is not a Python interpreter but rather a superset of the Python language that allows users to compile programs in the C language. The amazing thing is that it provides you with the combined power of both Python and C, and this, therefore, is why it can be used for writing C extensions as well as transform and tune your Python code into C. Hence, Cython overcomes many limitations of Python and still maintains the convenience and comfort that comes with Python.
Python has enormously grown and expanded into various implementations, all of which have been developed to the cater the needs of different users. Throughout the time frame in which users might be working with the Python interface, they might come across several of these implementations, and therefore, it is important to know what exactly each of these is and where does their expertise lie.
]]>Django logging contains four types of configurations which are explained below.
1. Django Logger
The logger records the events when the application is executed, and the logging is called. The log entries are stored in a file by categorizing them in different log levels. Every log level indicates the severity of the events. The purposes of these log levels are mentioned below:
2. Django Handler
The main task of the handler is to transmit the log information that is stored in the log file. The logging module contains many types of handlers and multiple of them can be defined for the same logger.
3. Django Formatter
It is used to format the log data. The data of the handler cannot be sent directly to the log file and the handler data requires it to be converted by using the formatter before sending. The formatter converts the log records into the string. The format of the data depends on the business logic of the handler.
4. Django Filter
It is used to filter the log messages. It is unnecessary to store all log messages into the log file. Different handlers can be used for different messages and the required log messages can be filtered using the required filters.
Before practicing the script of this tutorial, you must complete the following tasks:
Open the settings.py file from the Django project folder and add the following content to define the logging information. The properties of the handlers and loggers are set here. According to the logging property values, DEBUG level logging information will be stored in a log file named djangoapp.log when the Django app will be executed.
Open the djangoapp.log file to check log entries are stored in the file or not.
Logging information can be defined using the view file also. Open the views.py file from the logapp folder and replace the content with the following script. In this script, formatters, handlers, and loggers parts of Django logging are defined in the config.dictConfig() method. DEBUG level logging information will be stored in a log file named djangoapp.log and will be printed in the console when the Django app will be executed. index() function is used to send a simple headline text to the browser and the display_log() function is defined to send a simple text in the terminal and a headline text to the browser.
views.py
Modify the content of the urls.py file with the following script. In the script, the empty path(”) path is defined to call the index() function of the views and the ‘log/’ path is used to call the display_log() function of the views.
urls.py
Run the following URL to display the index page.
Run the following URL to call the display_log() method that will display a text message in the browser and a text message in the terminal. Log entries will be appended in the djangoapp.log file.
Two ways of using python logging in the Django application to keep the DEBUG level logging information are shown in this tutorial. The basic concept regarding Django logging is expected to be understood by the readers after reading this tutorial.
]]>Before practicing the examples of this tutorial, you must complete the following tasks:
A. Run the following command to create a Django app named filterapp.
B. Run the following command to create the user for accessing the Django database. If you have created the user before then don’t need to run the command.
C. Add the app name in the INSTALLED_APP part of the py file.
D. Create a folder named templates inside the filterapp folder and set the template’s location of the app in the TEMPLATES part of the py file.
Open the models.py file from the filterapp folder and add the following script to define the structure of employees tables. Employee class is defined to create a table named employees with name, post, email, department, and joining_date fields. Here, name, post, and department fields will store character data, the email field will store the email address and the joining_date field will store date data.
models.py
Run the makemigrations command to create a new migration based on the changes made by the models.
Run the migrate command to execute the SQL commands and create all tables in the database that are defined in the models.py file.
Modify the content of the admin.py file with the following content. Here, the Employee class of the models is registered using the register() method to display the records of employees tables in the Django administration dashboard.
admin.py
Run the following URL to open the Django admin login page. Provide the valid username and password to open the Django Administration Dashboard to access the database tables.
Insert two or more Employee records to apply the filter on the data. Here five records are inserted.
Create the search.html file inside the filterapp/templates/ folder with the following script. The data from the employee table will be displayed in this template file. for loop is used to read the content of the object_list variable that will be passed from the view file. The name, post, and department values of the employees table will be displayed by using the list.
search.html
Open the views.py file from the filterapp folder and modify the content of the file with the following script. Model and template names are defined in the script.
views.py
Modify the content of the urls.py file with the following content. In the script, the ‘searchEmp’ path is defined to call the SearchEmployee.as_view() method that will send all data and the filtered data of the employees table to the template file.
urls.py
The following output will appear without applying any filtering for the following URL.
http://localhost:8000/SerachEmp
Add the following line at the end of the views.py file to filter the records of the employees table where the value of the post field is ‘Accountant’.
The following output will appear after applying basic filtering.
Add the following line at the end of the views.py file to filter the records of the employees table where the value of the department field is ‘HT’ and the email field is ‘[email protected]’.
The following output will appear after applying multiple filtering.
Add the following line at the end of the views.py file to filter the records of the employees table where the value of the post field is ‘Manager’ or the value of the department field is ‘Sales’.
The following output will appear after applying Q object filtering.
Add the following line at the end of the views.py file to filter the records of the employees table where the value of the department field will be checked first and if it returns true then the value of the name field will be checked.
The following output will appear after applying filter chaining.
The data can be filtered in Django in many ways based on the application requirements. Four different ways of filtering were explained in this tutorial to understand the basics of Django filtering. These are simple filtering, multiple filtering, filtering with Q object, and filter chaining.
]]>How the Django template can be created and how the DTL can be used to add static or dynamic content to the template have been shown in this tutorial.
There are many benefits of using DTL in Django templates. Some of them are mentioned below.
Before practicing the script of this tutorial, you have to complete the following tasks:
Run the following command to create a Django app named tempapp:
Run the following command to create the user for accessing the Django database, but if you have created the user before, then don’t need to run the command shown below:
Add the app name in the INSTALLED_APP part of the settings.py file, as shown below:
Create a folder named templates inside the tempapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file, as shown below:
Create the index.html file inside the tempapp/templates/ folder with the following HTML script to display the formatted static text of two lines in the browser. HTML file can’t be displayed directly in the browser and the views.py file is used to render the HTML file in the Django application.
index.html
Open the views.py file from tempapp folder and add the following script. The rander() method is used in the views.py file to display any template file into the browser.
In the following script, the index() function is defined to display the content of the index.html file. When this function call from the urls.py file, then the template file will be displayed in the browser.
views.py
Modify the content of the urls.py file with the following script. According to the script, the index() function of the views.py will be called for the path, ‘index/’.
urls.py
Run the following URL from the browser to get the following output. The static data is displayed in the output.
http://localhost:8000/index/
Create the customers.html file inside the tempapp/templates/ folder with the following HTML script. DTL is used in this script to display the data of the dictionary variable that is initialized by the data of nested lists in the views2.py file. The first for loop is used to read the values of the outer list and the second for loop is used to read the values of the inner list.
customers.html
Create another view file named views2.py under tempapp folder with the following script. A dictionary variable named data is declared in the script that contains a nested list to generate tabular data of 4 rows and 4 columns. The data variable will be sent to the template when the customers() function of this script will be called from the urls.py file.
views2.py
Modify the urls.py file with the following script. ‘customers/’ path is defined in the script to load the customers.html file in the browser with the data of the dictionary.
urls.py
Run the following URL from the browser to get the following output. The records of all customers from the database tables have been displayed in the browser using the DTL.
http://localhost:8000/customers/
The ways of creating a simple template and a template with Django Template Language (DTL) have been shown in this tutorial. The new Django users will be able to create the template for the Django app properly after practicing the script of this tutorial.
]]>How HTML form can be used to take data from the user, read the input values, and print the values in the browser using Django is shown in this tutorial.
You have to create a Django project before creating the Django form. To create a new Django project and go to the project folder, run the following commands:
To create necessary files and apply migrations for the project, run the following command:
To check if the Django server is working properly or not, run the following command:
To create the formapp under django_pro project, run the following command:
Open the views.py file that is inside formapp folder and modify its content with the following content. The following script will check whether the form is submitted or not. If the form is submitted then the value of the request.method will be POST and request.POST.get() method is used to read its submitted values. The is_valid() function will check whether the data of the form is valid or not. If this function returns true, then a success message with the valid user’s data will be printed in the browser, otherwise, the error message that appears on the particular field of the form will be displayed. Other than that, the render() method is used to load the form in the browser and HttpResponse() method is used to send the response from the server to the browser after submitting the form.
Create forms.py inside the formapp folder and add the following content. The following script will create a form of four fields. The name field is defined to take the character data and it can be 40 characters long. The email field is defined to take any valid email address using the character data and it can be 50 characters long. The username field is defined to take the character data, and it can be 20 characters long. The password field is defined to take the character data and it can be a minimum of 10 characters and a maximum of 20 characters long. The forms.PasswordInput widget is used for the password field to hide the content of the password field.
Create a folder named templates inside the formapp folder. Go to the TEMPLATES section of the settings.py file and set the location of the template folder for the DIRS property.
settings.py
Create form.html inside the template folder with the following content.
{% csrf_token %} is used in the HTML script to prevent CSRF(Cross-Site Request Forgeries) attacks. {{ form.as_p }} will load the Django form that is designed by the forms.py file. When the Submit button is pressed, the form data will be submitted to the server.
Open the urls.py from the django_pro folder and modify the content with the following content.
Here, the ‘register/’ path is used to load the form in the browser.
Open any browser and type the following URL to load the user registration form in the browser.
http://localhost:8000/register
The following output will appear after running the URL. The validation for the empty field, the maximum length value of name, email, and password fields, and the minimum and maximum length values of the password field will be checked after submitting the form.
The following output shows that the password field is invalid. According to the form, the length of the password value must be within 10 to 20 characters. 5 characters have been given as input in the following form. For this, the form is showing the error message.
After entering the valid output in every field of the form, the following output will appear.
The way of creating a very simple user registration form in the Django application has been shown in this tutorial. Django has many methods for creating different types of fields of the form, such as CharField(), EmailField(), TextFiled, etc. The form validation task becomes very easier when the form is designed by Django form.
]]>Django framework can be used to create a web application with a database by writing script in models.py and views.py files of the Django app. The data can be inserted into the database tables by using Django Administration Dashboard or by writing a script in the views.py file. Django Administration Dashboard requires a login for an authenticated user to access the tables of the database. Single or multiple records can be inserted into the database tables by writing a script. bulk_create() method is one of the ways to insert multiple records in the database table. How the bulk_create() method is used to insert the multiple data in a Django database table will be shown in this tutorial.
Before practicing the script of this tutorial, you have to complete the following tasks:
Run the following command to create a Django app named bookapp.
Run the following command to create the user to access the Django database. If you already created one, then you don’t need to run the command.
Add the app name in the INSTALLED_APP part of the settings.py file.
Create a folder named templates inside the bookapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file.
Open the models.py file from the bookapp folder and add the following script to define the structure of books tables. Book class is defined to create a table named books with title, author, price, and published_year fields. According to the script, title and author fields will store character data, and price and published_year fields will store the integer data. Here, the title field is defined with the unique attribute. That means that the value of the title field will not accept any duplicate data.
Run the makemigrations command to create a new migration based on the changes made by the models.
Run the migrate command to execute the SQL commands and create all tables in the database that are defined in the models.py file.
Modify the content of the admin.py file with the following content. Here, the Book class of the models is registered using the register() method to display the books tables in the Django administration dashboard.
Create a template file named DisplayBookList.html inside the bookapp/templates/ folder with the following script. This script will display all data of books table in tabular form. Other than that, for loop is used in the script to iterate the data passed from the views.py file.
Modify the content of the views.py file with the following script. The model and template names are defined in the BulkInsert class. get_queryset() method of the class is defined in the script to return all records of the books table. On the other hand, Book.objects.all() method is used to return all records of the books table. exists() method is used in the script to check the books table is empty or not. If this method returns False then five records will be inserted into the books table using the bulk_create() method.
Modify the content of the urls.py file with the following script. In the script, the ‘admin/’ path is defined to open the Django Administration Dashboard and the ‘books/’ path is defined to call the BulkInsert.as_view() method that will insert five records to the books table and return the records to the template file.
Open the Django Administration Dashboard to check whether the data is inserted properly or not using the bulk_create() function.
The inserted records of the books table will be displayed in the browser after executing the following URL.
Multiple records can be inserted into the Django database table in different ways using the bulk_create(). A simple way of inserting multiple records in the database table using this method was shown in this tutorial to help Django users understand the logic behind the process.
]]>Before practicing the script shown in this tutorial, be sure to complete the following tasks.
Run the following command to create a Django app named socketapp:
Run the following command to install the channel:
Add the channels and app name to the INSTALLED_APP part of the settings.py file:
Define the value of ASGI_APPLICATION in the settings.py file:
Create a folder named templates inside the socketapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file:
The following output will appear in the terminal after running the Django server. The output shows that ASGI/Channels version 3.0.3 is running.
Create a template file named index.html in the defined template location to display the data sent by the WebSocket. The socket object that is created using JavaScript will read the data using the JSON.parse() method, then pass the value into the content of the <h1> tag that contains the ID value, ‘msg.’
index.html
Modify the views.py file of the socketapp with the following content. The index.html template file will be displayed in the browser with the text variable when the index() method of this script is called from the urls.py file. If no message is transmitted from the socket, then the text ‘LinuxHint’ will be displayed in the browser.
views.py
Modify the urls.py file of the socketapp with the following content. Two paths are defined in the script: the ‘admin/’ path is used to open the Django Administration Dashboard, and the ‘msg/‘ path is used to read the WebSocket message.
urls.py
When the following URL is executed without defining the consumer and routing files, the HTTP protocol will work and the following output will appear.
Now, create a consumers.py file inside the socketapp folder with the following script. The connect() method of ws_consumer will be used to accept the socket connection, read the current time value every second, and send the current time in JSON format via WebSocket when this method is called from the routing file.
consumers.py
Create the routing.py inside the socketapp folder with the following script. The ‘msg/’ path is defined in the script to call the consumer for sending the data to the socket.
routing.py
Modify the asgi.py file with the following script. The modules that are required to handle HTTP and WebSocket requests are imported in the script.
asgi.py
Now, run the following URL from the browser again to read the data from the WebSocket.
If the consumer and router are working properly, then the following digital clock will be displayed in the browser. Here, the router has sent the WebSocket request using the ‘msg/‘ path to the consumer that has accepted the request and sent the data to the template to show the digital clock in the browser where the second value of the current time is updating every second.
This tutorial showed you how to implement a real-time application using the Django framework and channels by creating a simple digital clock. Other types of real-time applications can also be implemented using Django and channels, such as online chatting systems. The scripts used in this tutorial work for Django versions 3+ and Channel versions 3+ only. So, if you are using an earlier Django or Channel version, then you will need to upgrade the version before testing the script provided in this tutorial.
]]>In this article, we will explore various data plotting methods by using the Pandas python. We have executed all examples on the pycharm source code editor by using the matplotlib.pyplot package.
In Pandas, the .plot() has several parameters that you can use based on your needs. Mostly, using the ‘kind’ parameter, you can define which type of plot you will create.
The following syntax is used to plot a DataFrame in Pandas Python:
You can also define the plot kind by using the kind parameter as follows:
Pandas DataFrames objects have the following plot methods for plotting:
If a user only uses the plot() method without using any parameter then, it creates the default line graph.
We will now elaborate on some major types of plotting in detail with the help of some examples.
In this type of plotting, we have represented the relationship between two variables. Let’s take an example.
For example, we have data of correlation between two variables GDP_growth and Oil_price. To plot the relation between two variables, we have executed the following piece of code on our source code editor:
The line chart plot is a basic type of plotting in which given information displays in a data points series that are further connected by segments of straight lines. Using the Line charts, you can also show the trends of information overtime.
In the below-mentioned example, we have taken the data about the past year’s inflation rate. First, prepare the data and then create DataFrame. The following source code plots the line graph of the available data:
In the above example, you need to set the kind= ‘line’ for line chart plotting.
The above example, you can also implement using the following method:
The following line graph will display after running the above code:
The bar chart plotting is used to represent the categorical data. In this type of plot, the rectangular bars with different heights are plotted based on the given information. The bar chart can be plotted in two different horizontal or vertical directions.
We have taken the literacy rate of several countries in the following example. DataFrames are created in which ‘Country_Names’ and ‘literacy_Rate’ are the two columns of a DataFrame. Using Pandas, you can plot the information in the bar graph shape as follows:
You can also implement the above example using the following method. Set the kind=’bar’ for bar chart plotting in this line:
You can also plot the data on horizontal bars by executing the following code:
In df.plot.barh(), the barh is used for horizontal plotting. After running the above code, the following bar chart displays on the window:
A pie chart represents the data in a circular graphic shape in which data displays into slices based on the given quantity.
In the following example, we have displayed the information about ‘Earth_material’ in different slices on the Pie chart. First, create the DataFrame, then, by using the pandas, display all details on the graph.
The above source code plots the pie graph of the available data:
In this article, you have seen how to plot DataFrames in Pandas python. Different kinds of plotting are performed in the above article. To plot more kinds such as box, hexbin, hist, kde, density, area, etc., you can use the same source code just by changing the plot kind.
]]>In this article, we will walk through the basic uses of a group by function in panda’s python. All commands are executed on the Pycharm editor.
Let’s discuss the main concept of the group with the help of the employee’s data. We have created a dataframe with some useful employee details (Employee_Names, Designation, Employee_city, Age).
Using the groupby function, you can concatenate strings. Same records can be joined with ‘,’ in a single cell.
In the following example, we have sorted data based on the employees ‘Designation’ column and joined the Employees who have the same designation. The lambda function is applied on ‘Employees_Name’.
When the above code is executed, the following output displays:
Use the groupby object into a regular dataframe by calling ‘.to_frame()’ and then use reset_index() for reindexing. Sort column values by calling sort_values().
In this example, we will sort the Employee’s age in ascending order. Using the following piece of code, we have retrieved the ‘Employee_Age’ in ascending order with ‘Employee_Names’.
There are a number of functions or aggregations available that you can apply on data groups such as count(), sum(), mean(), median(), mode(), std(), min(), max().
In this example, we have used a ‘count()’ function with groupby to count the Employees who belong to the same ‘Employee_city’.
As you can see the following output, under the Designation, Employee_Names, and Employee_Age columns, count numbers that belong to the same city:
By using the ‘import matplotlib.pyplot’, you can visualize your data into graphs.
Here, the following example visualizes the ‘Employee_Age’ with ‘Employee_Nmaes’ from the given DataFrame by using the groupby statement.
To plot the stacked graph using groupby, turn the ‘stacked=true’ and use the following code:
In the below-given graph, the number of employees stacked who belong to the same city.
You can also change the aggregated column name with some new modified name as follows:
In the above example, the ‘Designation’ name is changed to ‘Employee_Designation’.
Using the groupby statement, you can retrieve similar records or values from the dataframe.
In the below-given example, we have group data based on ‘Designation’. Then, the ‘Staff’ group is retrieved by using the .getgroup(‘Staff’).
The following result displays in the output window:
Similar data can be displayed in the form of a list by using the groupby statement. First, group the data based on a condition. Then, by applying the function, you can easily put this group into the lists.
In this example, we have inserted similar records into the group list. All the employees are divided into the group based on ’Employee_city’, and then by applying the ‘Lambda’ function, this group is retrieved in the form of a list.
The employees are grouped according to their age, these values added together, and by using the ‘transform’ function new column is added in the table:
We have explored the different uses of groupby statement in this article. We have shown how you can divide the data into groups, and by applying different aggregations or functions, you can easily retrieve these groups.
]]>The “split()” method can be used to split words using a user specified separator. It returns a list of splitted words without including the separator. If no separator is specified by the user, whitespace (one or more) is used as a single separator.
For instance, the code below will return “[‘Linux’, ‘Hint’]” as output:
The code below will return “[‘LinuxHint’, ‘com’]” as output when “.” is used as separator:
The separator doesn’t have to be a single character. The split method takes two arguments:
Both these arguments are optional. As mentioned above, if the “sep” argument is not specified, whitespace is used as a separator for splitting. The “maxsplit” argument has a default value of “-1” and it splits all occurrences by default. Consider the code below:
It will return “[‘LinuxHint’, ‘co’, ‘us’]” as output. If you want to stop splitting at the first occurrence of the separator, specify “1” as the “maxsplit” argument.
The code above will return “[‘LinuxHint’, ‘co.us’]” as output. Just specify the number of occurrences where you want the split process to stop as the second argument.
Note that if there are consecutive separators, an empty string will be for returned for the remaining separators after the first split (when “maxsplit” argument is not used):
The code above will return “[‘LinuxHint’, ”, ‘com’]” as output. In case you want to remove empty strings from the resulting list, you can use the following list comprehension statement:
You will get “[‘LinuxHint’, ‘com’]” as the output after running the above code sample.
Note that the “split()” method moves from left to right to split strings into words. If you want to split string from right to left direction, use “rsplit()” instead. Its syntax, usage and arguments are exactly the same as the “split()” method.
If no separator is found in the string while using “split()” or “rsplit()” methods, the original string is returned as the sole list element.
The “partition()” method can be used to split strings and it works identical to the “split()” method with some differences. The most notable difference is that it retains the separator and includes it as an item in the resulting tuple containing splitted words. This is especially useful if you want to divide the string into an iterable object (tuple in this case) without removing any original characters. Consider the code below:
The above code sample will return “(‘LinuxHint’, ‘.’, ‘com’)” as the output. If you want the result to be of list type, use the following code sample instead:
You should get “[‘LinuxHint’, ‘.’, ‘com’]” as output after running the above code sample.
The “partition()” method takes only one argument called “sep”. Users can specify a separator of any length. Unlike the “split()” method, this argument is mandatory, so you can’t omit the separator. However, you can specify whitespace as a separator.
Note that the partition method stops at the first occurrence of the separator. So if your string contains multiple separators, the “partition()” method will ignore all other occurrences. Here is an example illustrating this:
The code sample will produce “[‘LinuxHint’, ‘.’, ‘co.us’]” as output. If you want to split at all occurrences of the separator and include the separator in the final list as well, you may have to use a “Regular Expression” or “RegEx” pattern. For the example mentioned above, you can use a RegEx pattern in the following way:
You will get “[‘LinuxHint’, ‘.’, ‘co’, ‘.’, ‘us’]” as output after executing the above code sample. The dot character has been escaped in the RegEx statement mentioned above. Note that while the example above works with a single dot character, it may not work with complex separators and complex strings. You may have to define your own RegEx pattern depending on your use case. The example is just mentioned here to give you some idea about the process of retaining the separator in the final list using RegEx statements.
The “partition()” method can sometimes leave empty strings, especially when the separator is not found in the string to be splitted. In such cases, you can use list comprehension statements to remove empty strings, as explained in the “split()” method section above.
After running the above code, you should get “[‘LinuxHint’]” as output.
For simple and straightforward splits, you can use “split()” and “partition()” methods to get iterable types. For complex strings and separators, you will need to use RegEx statements.
]]>Pandas DataFrame is a 2D (two dimensional) annotated data structure in which data is aligned in the tabular form with different rows and columns. For easier understanding, the DataFrame behaves like a spreadsheet that contains three different components: index, columns, and data. Pandas DataFrames are the most common way to utilize the panda’s objects.
Pandas DataFrames can be created using different methods. This article will explain all possible methods through which you can create Pandas DataFrame in python. We have run all examples on the pycharm tool. Let’s start the implementation of each method one by one.
Follow the following syntax while creating DataFrames in Pandas python:
Example:Let’s explain with an example. In this case, we have stored the data of student’s names and percentages in a ‘Students_Data’ variable. Further, using the pd.DataFrame (), we have created a DataFrames for displaying student’s result.
Pandas DataFrames can be created using the different ways that we will discuss in the rest of the article. We will print the Student’s courses result in the form of DataFrames. So, using one of the following methods, you can create similar DataFrames that are represented in the following image:
In the following example, DataFrames are created from the dictionaries of lists related to student’s course results. First, import a panda’s library and then create a dictionary of lists. The dict keys represent the column names such as ‘Student_Name’, ‘Course_Title’, and ‘GPA’. Lists represent the column’s data or content. The ‘dictionary_lists’ variable contains the data of students that are further assigned to the ‘df1’ variable. Using the print statement, print the all content of DataFrames.
Example:
After executing the above code, the following output will be displayed:
The DataFrame can be created from the dict of array/list. For this purpose, the length must be the same as all the narray. If some index is passed, then the index length should be equal to the array’s length. If no one index is passed, then, in this case, the default index to be a range (n). Here, n represents the array’s length.
Example:
In the following code, each line represents a single row.
Example:
In the following code, each dictionary represents a single row and keys that represent the column names.
Example:
The dict keys represent the names of columns and each Series represents column contents. In the following lines of code, we have taken three types of series: Name_series, Course_series, and GPA_series.
Example:
Different lists can be merged through the list(zip()) function. In the following example, pandas DataFrame are created by calling pd.DataFrame() function. Three different lists are created that are merged in the form of tuples.
Example:
Using the above methods, you can create Pandas DataFrames in python. We have printed a student’s course GPA by creating Pandas DataFrames. Hopefully, you will get useful results after running the above-mentioned examples. All programs are commented well for better understanding. If you have more ways to create Pandas DataFrames, then do not hesitate to share them with us. Thanks for reading this tutorial.
]]>We will explore the uses of merge function, concat function, and different types of joins operations in Pandas python in this article. All examples will be executed through the pycharm editor. Let’s start with the details!
The basic commonly used syntax of merge () function is given-below:
Let’s explain the details of the parameters:
The first two df_obj1 and df_obj2 arguments are the names of the DataFrame objects or tables.
The “how” parameter is used for different types of join operations such as “left, right, outer, and inner”. The merge function uses “inner” join operation by default.
The argument “on” contains the column name on which the join operation is performed. This column must be present in both DataFrame objects.
In the “left_on” and “right_on” arguments, “left_on” is the name of the column name as the key in the left DataFrame. The “right_on” is the name of the column used as a key from the right DataFrame.
To elaborate on the concept of joining DataFrames, we have taken two DataFrame objects- product and customer. The following details are present in the product DataFrame:
The customer DataFrame contains the following details:
We can easily find products sold online and the customers who purchased them. So, based on a key “Product_ID”, we have performed inner join operation on both DataFrames as follows:
The following output displays on the window after running the above code:
If the columns are different in both DataFrames then, explicitly write the name of each column by the left_on and right_on arguments as follows:
The following output will show on the screen:
In the following examples, we will explain four types of Joins operations on Pandas DataFrames:
We can perform an inner join on multiple keys. To display more details about the product sales, take Product_ID, Seller_City from the product DataFrame and Product_ID, and “Customer_City” from the customer DataFrame to find that either seller or customer belongs to the same city. Implement the following lines of code:
The following result shows on the window after running the above code:
Outer joins return both right and left DataFrames values, which either have matches. So, to implement the outer join, set the “how” argument as outer. Let’s modify the above example by using the outer join concept. In the below code, it will return all values of both left and right DataFrames.
Set the indicator argument as “True”s. You will notice that the new “_merge” column is added at the end.
As you can see in the below screenshot, the merge column values explain which row belongs to which DataFrame.
Left join only display rows of the left DataFrame. It is similar to the outer join. So, change the ‘how’ argument value with “left”. Try the following code to implement the idea of Left join:
The right join keeps all right DataFrame rows to the right along with the rows that are also common in the left DataFrame. In this case, the “how” argument is set as the “right” value. Run the following code to implement the right join concept:
In the following screenshot, you can see the result after running the above code:
Two DataFrames can be joined using the concat function. The basic syntax of the concatenation function is given below:
Two DataFrames objects will pass as arguments.
Let’s join both DataFrames product and customer through the concat function. Run the following lines of code to join two DataFrames:
In this article, we have discussed the implementation of merge () function, concat () functions, and joins operation in Pandas python. Using the above methods, you can easily join two DataFrames and learned. how to implement the Join operations “inner, outer, left, and right” in Pandas. Hopefully, this tutorial will guide you in implementing the join operations on different types of DataFrames. Please let us know about your difficulties in case of any error.
]]>The following sections provide examples that illustrate how to implement two different applications using the QTimer class.
The following script will implement a stopwatch application in Python using the QTimer class. This application will count the number of seconds and the number of minutes. Two buttons are used to start, stop, resume, and reset the counter. When the user clicks the Start button, the counter will start counting, and the caption of the Start button will be changed to Stop. When the user clicks the Start button with the caption Stop, the counter will stop temporarily, and the caption of the Start button will be changed to Resume to continue the counter to the next time. When the user clicks the Reset button, all the values of the counter will be initialized to 0.
The following window will appear after the above script is executed.
The stopwatch will start working after the user clicks the Start button.
The counter will stop counting after the user clicks the Stop button.
The following script will implement a digital clock in Python using the QTimer class. The script will display the digital clock in a label by reading the current system time once every second.
The following output window will appear after the above script is executed.
The date and time value of the current system time can be read in various ways using the QTimer class of the PyQt library. The QTimer class was used in this tutorial to execute various example time-related scripts.
]]>The QTableWidget class includes many methods to perform tasks related to table creation. Some of the more commonly used methods of this class are explained below:
Method Name | Purpose |
---|---|
setRowCount() | Used to define the number of rows. |
setColumnCount() | Used to define the number of columns. |
setHorizontalHeaderLabels() | Used to set the header labels of the table. |
setItem() | Used to set the cell value of the table. |
resizeColumnsToContents() | Used to resize the columns of the table based on the content. |
resizeRowsToContents() | Used to resize the rows of the table based on the content. |
setMinimumWidth() | Used to set the minimum width of the table. |
setMinimumHeight() | Used to set the minimum height of the table. |
show() | Used to display the table. |
The following sections provide simple examples to explain how to create a table in the PyQt application using static data and list data.
The following script creates a table of static data with five rows and four columns using the QTableWidget class. Two for loops with range values have been used in the script to add the static data into the table cells. The row and column positions of each cell have been added as the content of each cell. The QDesktopWidget is used in the script to display the window with the table in the center of the screen.
The following window with a table will appear the above script is executed. According to the values of the for loops, the cell value of the first row and the first column is ‘Row-1, Col-1,’ and the cell value of the last row and last column is ‘Row-5, Col-4.’
The following script creates a table with the content of a Python dictionary and list using the QTableWidget class. The script also adds a tool-tip text for the table header. A Python dictionary named marks is also declared in the script. The course codes are used as the key values of the dictionary. A Python list is declared to define the student IDs. The key values of the dictionary are added to the header of the table, the values of the list are added to the first column of the table, and the values of the dictionary are added to the other columns of the table.
The following window with the table will appear after the above script is executed.
This tutorial showed you how to create tables with fixed data, dictionary data, and list data using two examples. Tables can also be created with dynamic data using database tables or other data sources.
]]>The QPushButton class has many methods to perform various button-related tasks. Some of the more commonly used methods of this class are mentioned below:
Method Name | Purpose |
---|---|
text() | Used to read the caption of the button. |
setText() | Used to set text in the caption of the button. |
setIcon() | Used to set an icon in the caption of the button. |
setDefault() | Used to set the default button. |
setEnabled() | Used to enable or disable buttons. A value of True is used to enable the button, and a value of False is used to disable the button. |
setCheckable() | Used to identify whether the button is pressed or released. |
isChecked() | Used to read the state of the button that is a boolean value. |
toggle() | Used to toggle between states. If the current value of the button state is True, then the value will change to False, and vice versa. |
The following sections provide several simple examples to explain the usage of QPushButton.
The following script is used to create a single button in the window. The script will attach a custom function with the clicked event of the button to check whether the button has been clicked. The window will display a button following the execution of the code. If the user clicks the button, the text ‘Button is pressed’ will show in the label.
The following window will appear after executing the script.
If the user clicks the Çlick Me button, then the following text will appear in the caption beneath the button.
The following script will create multiple pushbuttons using the QPushButton class. Two buttons are created in the script. The clicked event of the ‘Yes’ button is attached to a method named btn1_onClicked(), and the clicked event of the ‘No’ button is attached to a method named btn2_onClicked(). A caption created below the buttons will display the specified message based on the button clicked by the user. The setGeometry() function is used for each label and button to set the position of the objects in the window.
The following window will appear after executing the script.
If the user clicks the Yes button, the message, ‘You clicked Yes’ will be displayed as the label text.
If the user clicks the No button, the message, ‘You clicked No’ will be displayed as the label text.
The QPushButton class allows users to create one or more buttons based on the application requirements. This tutorial showed the usage of this class for creating one or multiple buttons, as well as how to handle click events of buttons using custom event handler functions.
]]>The QMessageBox class has many methods for creating various types of message boxes. Some of the more commonly used methods of the QMessageBox class are described below:
Method Names | Purpose |
---|---|
setTitle() | Used to display the custom title. |
setText() | Used to set the text of the main message. |
setDetailText() | Used to display a window with a details button; the message text will appear after the user clicks on the button. |
setInformativeText | Used to display the additional message. |
setIcon() | Used to set an icon in the message box based on the message type. |
setWindowTitle() | Used to set the title of the message window. |
setDefaultButton() | Used to set the button in the message box default; the button will release a clicked signal when the Enter key is pressed. |
setEscapeButton() | Used to set any button to work as an escape key; the button will release a clicked signal when the Escape key is pressed. |
setStandardButtons() | Various standard buttons can be used in the message box based on the message type, such as OK, Yes, No, Cancel, Close, etc. |
The following sections of this tutorial provide examples that will show you how to create different message boxes using the QMessageBox class.
The following script will create a simple informational message box using the QMessageBox class. This type of message box provides the informational message for the user only. OK is the default button in the message box. Here, QMessageBox.Information is used in the setIcon() method to display the information icon in the message box.
The following message box will appear after the above script is executed.
The following script will create the warning message box using the QMessageBox class. This type of message box provides the warning message for the user. The warning is used in the setIcon() method to display the warning icon in the message box. The OK and Cancel buttons are added to the message box using the setStandardButtons() method. A custom method called msgButton() is defined in the class to trace the button in the message box that has been clicked by the user. If the user clicks the OK button, then the text, ‘OK button is pressed,’ will print; otherwise, the ‘Cancel button is pressed’ text will print.
The following message box will appear after the above script is executed.
If the user clicks the OK button, the following output will appear.
The following script will create the question message box using the QMessageBox class. This type of message box provides the question message for the user to take the particular action based on the user’s decision. Here, QMessageBox.Question is used in the setIcon() method to display the question icon in the message box. The Yes and No buttons are added to the message box using the setStandardButtons() method. The No button is set as the default button using the setDefaultButton() method. A custom method called msgButton() is defined in the class to trace the button in the message box that has been clicked by the user.
The following message box will appear after the above script is executed.
If the user clicks the Enter key without selecting any buttons, then the No button will be activated by default, and the following output will appear:
In this tutorial, three different types of message boxes were created using the QMessageBox class. Hopefully, this tutorial helped you to better understand the usage of this class. You should now be able to create a message box for the PyQt application.
]]>A ComboBox is used to select one item from a list of items, much like the radio button. The QComboBox class of PyQt is used to create drop-down lists using Python script. It brings up a list of items for the user to select. The items of the ComboBox can be added, changed, and removed using the script. Multiple items can be selected like the CheckBox button from the list of items from the ComboBox then it is called ListBox. This tutorial shows you how to use QComboBox to create a drop-down list in Python.
The QComboBox class contains many methods for performing various tasks related to ComboBox. Some of the more commonly used methods of this class are described below:
Method Name | Purpose |
---|---|
count() | Used to count the total number of items in the list. |
addItem() | Used to add a single new item to the list. |
addItems() | Used to add multiple items to the list. |
itemText() | Used to read the text of a particular item based on an index. |
setItemText() | Used to set the text of a particular item based on an index. |
currentText() | Used to read the text of the selected item. |
currentIndex() | Used to read the index of the selected item. |
clear() | Used to delete all items from the list. |
highlighted() | Used when an item in the list is highlighted. |
activated() | Used when an item is selected by the user. |
currentIndexChanged() | Used when the item in the list has changed. |
The following sections provide examples that explain some different uses of the ComboBox using the QComboBox module of the PyQt library.
This example shows you how to create a simple drop-down list using the QComboBox class. Here, a drop-down list of five elements is created and is attached to a custom function that will print the selected value from the list. One label is used in the function of the drop-down list to display static text, and another label is used below the drop-down list to show the selected value.
If the user clicks on the drop-down list after executing the script, the following list will appear.
If the user selects the value Bash from the drop-down list, the value of the second label will be changed to ‘You have selected: Bash.’
In the previous example, the drop-down list was created with static data using the addItem() method of the QComboBox class. This example shows you how to add multiple items in the drop-down list by defining a Python list. First, we will add static text to the first item of the drop-down list using the addItem() method. Next, we will define a list of five elements in the script, and we will add these elements to the drop-down list using the addItems() method. A custom function is attached to the drop-down list to display the message in the label based on the user selection.
If the user clicks the drop-down list after executing the script, then the following list will appear.
If the user selects any item except the first item in the drop-down list, then the selected value will be shown in the label by combining with the other text.
If the user selects the first item in the drop-down list, then the value, ‘You have selected nothing’ will be shown in the label.
This article showed you how to create and use drop-down lists in Python using the QComboBox class using simple examples to help you to better understand the use of this class.
]]>PyQt is a popular Python library used to implement graphical applications in Python more easily. This library comes with a GUI (Graphical User Interface) builder tool called Qt Designer. The GUI can be built quickly in Python using the drag-and-drop feature of this library, though this tool has no debugging facility like the standard IDE. This tutorial shows you how to implement the GUI using the Qt Designer class of PyQt.
You must install the Qt Designer tool before practicing the examples provided in this tutorial. Run the following commands to install the Qt Designer on your system:
Run the following command to change the current directory location to the Qt Designer folder.
Run the following command to open the Qt Designer application.
If the Qt Designer has been installed properly, the following window will appear. The Widget box shown on the left side of the main window contains various widgets that you can use to design the user interface of the application. The New Form window is used to create a new window using the default buttons. The windows shown on the right side of the main window provides information about the widgets that can be read or modified.
To begin designing the interface for the Python application, we will click the Create button in the following window to open the dialog box with two default buttons.
Next, we will design a login form using the Label, Text Edit, and Push Button widgets. The dialog box will be saved with the name Login.ui, which will be used later in the Python script. The QObject name will be changed to Logindialog using the Property Editor Window of this application.
The user interface file created by the Qt Designer can be used in the Python script in two ways. The file can be used directly in the Python script, or the converted Python file of the Qt Designer file can be used in the Python script. Both ways of using the dialog box of Qt Designer are shown in the following section of the tutorial.
The UIC module of the PyQt library is used to load the file created by the Qt Designer, and the loadUI() method of the UIC module is used to load the UI file. The following script shows how to load the Qt Designer file named Login.ui that we created before. The necessary modules are imported at the beginning of the script. The object of the application is created using the QApplication(), and the Qt Designer file is loaded using the loadUI() method. Next, the exec() method is called to start the event loop of the application.
The following dialog box will appear after executing the above script.
The UI file created by the Qt Designer can be converted into a Python file using the pyuic5 command. Run the following command to convert the Login.ui file into the loginForm.py file. The Login.ui file must be stored in the current location to run the following command; otherwise, an error will be generated.
The following code will be generated in the loginForm.py file after executing the above command.
The following will display the Login dialog box by importing the loginForm.py file created using the pyuic5 command. The object of the application is created using QApplication(), and the Login dialog box is loaded using the setupUi() method. The Login button is attached with the loginClicked() method to check whether the username and password taken from the user are valid. The Cancel button is attached to the cancelClicked() method to quit from application. The exec() method is called to start the event loop of the application.
The following dialog box will appear after executing the above script.
If the user enters the wrong username or password in the Login form, then the following output will appear after clicking the Login button.
If the user enters the correct username and password in the Login form, then the following output will appear after clicking on the Login button.
If the user clicks the Cancel button in the Login form, then the dialog box will disappear.
This tutorial showed you how to install Qt Designer and how to design a simple form using this application. The tutorial also showed you how to load the UI dialog box directly and after converting it into the Python script have shown in the other part of this tutorial. Hopefully, this article helped you to better understand the usage of Qt Designer for building and using the GUI in applications.
]]>The steps of implementing a simple PyQt application to calculate the sum of two numbers are shown in this section of the tutorial. Here, the number values will be taken from the user using textboxes, after executing the script, then the sum of the values will be displayed after clicking a button. A window with the necessary fields has been created here to build the design of the application; next, the Python script is used to calculate the sum.
Steps:
You have to import the required modules of Python to design the PyQt application of this tutorial. To design this application, it will require two labels, two text boxes, and a push-button.
QApplication, QMainWindow, QLabel, QTextEdit, and QPushButton modules will be required to design the application.
Add the following lines at the beginning of the script to use these modules.
Add the following lines to create the application object and start the event loop. Nothing will appear after executing the script now.
Create the class to add the necessary objects in this step to design the application window.
Add the following lines to create a class with a window object. Here, the title, size, and position of the window are set. Next, the show() method is called to display the window as output.
You have to create the object of the class before running the event loop.
The following blank window will appear after executing the script.
Now, add the necessary objects required to implement the application. The three objects of the QLabel widget, two objects of the QTextEdit widget, and a button object of the QPushButton widget are created in this step. The first two label objects will be used to provide the helping text before the textboxes. QTextEdit objects will be used to take two number values from the user. QPushButton object will be created to calculate the sum of the input numbers using an event handler function that will be created in the next step. The last label object will be used to display the summation of the two numbers. Here, the setGeometry() function is called for every object to set the position of the object in the window.
The following output will appear after executing the script. No event handler function is created in this step, which is used to calculate the sum of the numbers. So, if the user clicks the button, nothing will happen.
Create a method named onClicked() with the following lines inside the addition class to handle the click event of the button. The values of the textboxes are converted into integer numbers using the int() function and stored into the num1 and num2 variables. Next, the sum of num1 and num2 are stored in the result variable. The values of num1, num2, and result variables are converted into string values using the str() function, before storing the values in the output variable. The third label object is used to display the content of the output variable.
Add the following lines in the class after the button object to call onClicked() method when the button will be clicked.
After executing the script, if the user entered 12 and 18 in the textboxes and clicked on the Calculate Sum button, and the following formatted output will appear below the button.
The implementation of a very simple PyQt application has been explained in this tutorial starting from the basic to help the new Python users. Hopefully, the user will be able to design and create a simple PyQt application after completing and understanding the steps of this tutorial properly.
]]>The scientific or numerical visualization tasks can be done in python easily using various Python libraries, such as Plotly, Matplotlib, Seaborn, ggplot, PyQt, etc. PyQtGraph is a useful module of the PyQt library to create a graph. This module can create graphs very fast. 2D and 3D graphics can be created by using this module. How to use the PyQtGraph module to draw different types of graphs has shown in this tutorial.
You have to install the PyQtGraph module in your system before creating the graph. Run the following command to install PyQtGraph by using pip3.
A line chart or line graph is a chart that displays information by using a series of data plots. PlotWidget widget is used to create all plots of PyQtGraph. This widget contains a canvas on which any plot can be added or removed.
The following script shows the way to draw a line graph using random numbers. range() function is used to generate 10 sequential numbers that are used for x-axis values. The random module of python is used to generate 10 random integer numbers used for y-axis values. plot() method is used to draw each plot of the line graph based on the values of the x-axis and y-axis. When the code is executed in interactive mode, then sys.flags.interactive flag will be True. If this flag’s value is not True, then it indicates that the Qt event loop does not require to run because the REPL (Run, Evaluate, Print, Loop) already has an event loop.
Output:
The following similar line graph will be appeared after executing the above script. The graph will vary in each execution for the random values.
The following script shows how to draw a stylist line graph based on the values of a python list. mkPen() function is used to set the color and width of the line. ‘o‘ is used as the marker in the graph, and the color and width of the marker are set by using symbolPen and symbolSize properties.
Output:
The following line graph will be appeared after executing the above script.
A set of data can be visualized by using a bar graph. A simple bar creates by comparing the list of data with a related range of data. BarGraphItem class is used to create the bar graph by using PyQtGraph.
The following script shows how to draw a bar graph based on the values of a NumPy array. BarGraphItem is used to draw a bar graph with blue color and a width value of 0.5.
Output:
The following bar graph will be appeared after executing the above script.
Creating three different types of graphs with random values, list items, and NumPy array have shown in this tutorial by using three simple examples. The readers will be able to use the PyQtGraph module for implementing line and bar graphs after reading this tutorial.
]]>The checkbox is used to select zero or more options from many options using the graphical user interface. A form with a checkbox can be created by using QCheckBox class in a Python script or using the QCheckBox widget of Qt Designer without writing any script.
When a form with a checkbox is created using QCheckBox class, then stateChanged.connect() function is called to apply the action done by the user’s input. If the user checked any checkbox option, then the value of QtCore.Qt.checked will be True. Multiple checkboxes with a single selection like Radio Button can be created using QbuttonGroup class.
How a form with a checkbox can be created by writing a Python script is shown in this tutorial.
QCheckBox class has many functions to do different types of tasks with the checkbox. Some most commonly used methods of this class are described below:
Method Name | Purpose |
---|---|
isChecked() | It returns a boolean value. When the user clicks to check the checkbox, it returns True, otherwise, it returns False. |
setChecked() | It is used to change the state of the checkbox. True value is set to make the checkbox checked, and False value is set to make the checkbox unchecked. |
text() | It is used to read the label of the checkbox. |
setText() | It is used to set the label of the checkbox. |
isTriState() | It returns a boolean value. It is used to check the tri-state to know whether the checkbox is enabled or not. |
setTriState() | It is used to enable the third state of the checkbox that indicates the neutral state. |
The uses of the checkbox are shown in this section using different types of examples. The use of a single checkbox, as shown in the first example, and the use of multiple checkboxes are shown in the second example.
The way of creating a single checkbox using QCheckBox class and reading the input value of the checkbox provided by the user are shown in this example. The necessary modules are imported at the beginning of the script. A label is used in the above checkbox for providing the information for the user. If the user clicks on the checkbox to check, then the script will print, “Wow! You like programming”, otherwise the script will print, “Oh no!, You don’t like programming”.
The following window with a checkbox will appear after executing the script.
In the following output, the user has checked the checkbox twice and unchecked the checkbox once.
The method of creating multiple checkboxes using QCheckbox class and reading multiple values of the multiple checkboxes are shown in this example. Two labels and three checkboxes are added to the window. The first label is added at the beginning of the checkboxes to provide information for the user, while the second label is added at the end of the checkboxes to display the values of the selected checkbox or checkboxes.
The following window will appear after executing the script. The default value of the second label is “Nothing is selected” and the value of the label will be changed when any checkbox is checked or unchecked by the user.
In the following output, two checkboxes are checked by the user, and the value of the second label is changed to “Chocolate, Pasta”.
The way of defining one or multiple checkboxes and reading the values of the selected checkbox(es) have been explained in this tutorial using two simple examples. The groups of checkboxes can be defined to select a particular checkbox from a group that is not shown here.
]]>Python has replaced many widely used programming languages like C++ and Java, demand for programmers having Python skills is increasing very rapidly. Anyone wishes to have a decorated career in data science, and machine learning must learn Python programming language.
There are abundant resources on Python programming available online for those who wish to learn Python-like online courses and tutorials. I have already shared an article on free online Python tutorials. Now I’m going to give you a brief introduction to the top 10 Python books beginners can refer. All the books listed here are available on Amazon.
Head First Python by Paul Barry is one of the highly-rated books on Amazon and rightly so. Paul Barry is a lecturer at the Institute of Technology, Carlow, Ireland. It is the perfect book for the beginner who wants to dive into Python programming language basics. Language of the book easy so that one can get easily comfortable in learning Python.
In the early part of the book, the author introduces you to the Python programming languages’ fundamentals and how to work with its built-in functions and data structures. And in the latter part, it slowly levels-up and introduces you to exception handling, web development, and other Python programming applications.
Ratings:
Goodreads: 3.83/5
Amazon: 4.5/5
Buy on Amazon: https://amzn.to/3crVWFz
Python Crash Course by Eric Matthes is the world’s best-selling guide to the Python programming language. It is one of the most sold and highly rated Python books on Amazon. Book is scripted well, and you will be programming in Python in absolutely no time.
This book will walk you through all the basics and fundamentals of Python programming and its applications. It covers Python libraries and tools that includes Pygame, Matplotlib and Django, guide to make 2D games and create/customize web apps and deploy them online.
Ratings:
Goodreads: 4.33/5
Amazon: 4.7/5
Buy on Amazon: https://amzn.to/36tJ6ml
Don’t get scared by the book’s title as it is completely opposite world once you enter the book. Book is perfect for newbies who want to learn Python 3. The approach by the author Zed Shaw makes it easier to learn the Python programming language.
The book is full of exercises that will sharpen your skills in Python programming and its fundamentals.
Ratings:
Goodreads: 3.91/5
Amazon: 4.4/5
Buy on Amazon: https://amzn.to/36wrxlT
Python Cookbook by David Beazley and Brian K. Jones is an ideal Python recipe book for a beginner to intermediate level programmers. Most of the book material focuses on advanced libraries, frameworks and applications.
Before diving into this book, you must have basic knowledge of Python programming. Some of the topics covered in this book are data structure and algorithms, iterators, generators, data encoding and processing, etc.
Ratings:
Goodreads: 4.16/5
Amazon: 4.6/5
Buy on Amazon: https://amzn.to/2NKuZmc
Written by John Zelle, Python Programming: An Introduction to Computer Science gives you introduction to the Python programming and introduces you to the world of programming. The book is ideal for beginners as it eases you into the world of computer science.
As the book focuses on computer science with Python programming language at its base, this book becomes ideal for anyone who wants to step into the world of software and web development.
Ratings:
Goodreads: 4.01/5
Amazon: 4.5/5
Buy on Amazon: https://amzn.to/36wUy0y
Author Paul Deitel and Harvey Deitel offer groundbreaking and flexible approach to computer science and data science. This book is ideal for both computer science and data science aspirants.
The book contains ample exercises, examples, implementation case studies and projects. It also introduces you to programming with AI, Big data, and the cloud, along with computer science and data science. It is one of the most highly rated books on Amazon.
Ratings:
Goodreads: 4/5
Amazon: 4.6/5
Buy on Amazon: https://amzn.to/3rdZJKZ
This is the collection of two books for beginners. First one is Python Programming for Beginners, and the second is Python Workbook. The second book will help you brush-up your Python skills.
This is a great combination of books for newbies who wish to learn Python programming. All the basics of Python programming are covered well in this book.
Ratings:
Goodreads: 4.62/5
Amazon: 4.3/5
Buy on Amazon: https://amzn.to/3cFFkdR
Python for Beginners is a Crash Coursebook by Timothy C. Needhamis that will make you learn Python programming language in one week. This book will introduce you to Python variables and directories.
This is one of the best books for beginners who want to learn Python and those newbies looking to learn to program.
Ratings:
Goodreads: 3.84/5
Amazon: 4.2/5
Buy on Amazon: https://amzn.to/2Mp1zcW
Python Tricks: A Buffet of Awesome Python Features is a trick book by Dan Bader. This book will help you discover Python’s best practices and take you one step closer to mastering Python programming.
This book is ideal for beginner to mid-level programmers who want to learn writing clean code and make most out of Python programming. You will discover hidden gold in Python libraries while going through this book.
Ratings:
Goodreads: 4.45/5
Amazon: 4.6/5
Buy on Amazon: https://amzn.to/2NNFNQt
Python Workbook: Learn Python in One Day and Learn It Well by Jamie Chan is Python workbook for beginners. It gives you a hands-on approach to learn Python programming fast. Book is a collection of in-depth course and practice questions to improve your Python skills.
When you finish this book, you will definitely feel confident about programming in Python language.
Ratings:
Goodreads: 3.85/5
Amazon: 4.4/5
Buy on Amazon: https://amzn.to/3tdWwwJ
These are the top 10 Python books for Python Programming Language for those beginners who want to have a career in programming and development. Feel free to share your views and queries with us at @linuxhint and @SwapTirthakar.
]]>Python NumPy library has many aggregate or statistical functions for doing different types of tasks with the one-dimensional or multi-dimensional array. Some of the useful aggregate functions are mean(), min(), max(), average(), sum(), median(), percentile(), etc. The uses of mean(), min(), and max() functions are described in this tutorial. The mean() function is used to return the arithmetic mean value of the array elements. The arithmetic mean is calculated by dividing the sum of all elements of the array by the total number of array elements. If the particular axis is mentioned in the function, then it will calculate the mean value of the particular axis. max() function is used to find out the maximum value from the array elements or the elements of the particular array axis. min() function is used to find out the minimum value from the array elements or the particular array axis.
The syntax of the mean() function is given below.
Syntax:
This function can take five arguments. The purposes of these arguments are described below:
input_array
It is a mandatory argument that takes an array as the value and the average of the array values is calculated by this function.
axis
It is an optional argument, and the value of this argument can be an integer or the tuple of integers. This argument is used for the multi-dimensional array. If the value of the axis is set to 0, then the function will calculate the mean of the column values, and if the value of the axis is set to 1, then the function will calculate the mean of the row values.
dtype
It is an optional argument that is used to define the data type of the mean value.
out
It is an optional argument and is used when the output of the function will need to store in an alternative array. In this case, the dimension of the output array must be the same as the input array. The default value of this argument is None.
keepdims
It is an optional argument, and any Boolean value can be set in this argument. It is used to transmit the output properly based on the input array.
This function returns an array of mean values if the value of the out argument is set to None, otherwise the function returns the reference to the output array.
The following example shows how the mean value of a one-dimensional and two-dimensional array can be calculated. Here, the first mean() function is used with a one-dimensional array of integer numbers, and the second mean() function is used with a two-dimensional array of integer numbers.
Output:
The following output will appear after executing the above script.
The syntax of the max() function is given below.
Syntax:
This function can take six arguments. The purposes of these arguments are described below:
input_array
It is a mandatory argument that takes an array as the value, and this function finds out the maximum value of the array.
axis
It is an optional argument, and its value can be an integer or the tuple of integers. This argument is used for the multi-dimensional array.
out
It is an optional argument and is used when the output of the function will need to store in an alternative array.
keepdims
It is an optional argument, and any Boolean value can be set in this argument. It is used to transmit the output properly based on the input array.
initial
It is an optional argument that is used to set the minimum value of the output.
where
It is an optional argument that is used to compare the array elements to find out the maximum value. The default value of this argument is None.
This function returns the maximum value for the one-dimensional array or an array of the maximum values for the multi-dimensional array.
The following example shows the use of the max() function to find out the maximum value of a one-dimensional array.
Output:
The following output will appear after executing the above script.
The syntax of the min() function is given below.
Syntax:
The purposes of the arguments of this function are the same as the max() function that has been explained in the part of the max() function. This returns the minimum value of the input array.
The following example shows the use of the min() function to find out the minimum value of a one-dimensional array.
Output:
The following output will appear after executing the above script.
The purposes of three useful aggregate functions (mean(), max(), and min()) have been explained in this tutorial to help the readers to know the ways of using these functions in python script.
]]>where the () function can take two arguments. The first argument is mandatory, and the second argument is optional. If the value of the first argument (condition) is true, then the output will contain the array elements from the array, x otherwise from the array, y. This function will return the index values of the input array if no optional argument is used.
Different types of Boolean operators can be used to define the condition of this function. The uses of where a () function with multiple conditions are shown in this part of the tutorial.
The following example shows the use of the where() function with and without the optional argument. Here, the logical OR has used to define the condition. The first where() function has applied in a one-dimensional array that will return the array of indices of the input array where the condition will return True. The second where() function has applied in two one-dimensional arrays will retrieve the values from the first array when the condition will return True. Otherwise, it will retrieve the values from the second array.
The following output will appear after executing the above script. Here, the condition has returned True for the values 23,11,18,33, and 38 of the first array. The condition has returned False for the values 45, 43, 60, 71, and 52. So, 42, 43, 44, and 48 have been added from the second array for the values 45, 43, 60, and 52. Here, 71 is out of range.
The following example shows how the () function can be used with the multiple conditions defined by logical and applied in two one-dimensional arrays. Here, two one-dimensional NumPy arrays have been created by using the rand() function. These arrays have been used in the where() function with the multiple conditions to create the new array based on the conditions. The condition will return True when the first array’s value is less than 40 and the value of the second array is greater than 60. The new array has printed later.
The following output will appear after executing the above script. The condition has returned False for all elements. So, the returned array contains the values from the second array only.
The following example shows how where the () function can be used with the multiple conditions defined by logical AND that will be applied in two multi-dimensional arrays. Here, two multi-dimensional arrays have been created by using lists. Next, these functions have applied in where() function to create the new array based on the condition. The condition used in the function will return True where the value of the first array is even and the value of the second array is odd; otherwise, the condition will return False.
The following output will appear after executing the above script. In the output, 43, 12, 7, 34, 9, 22, 41, 5, and 12 have added in the new array from the second array because the condition is False for these values. The first 12 value in the new array has added from the first array because the condition is True for this value only.
where the () function of the NumPy library is useful for filtering the values from two arrays. Creating a new array by filtering the data from two arrays based on multiple conditions defined by logical OR and logical AND has been explained in this tutorial. I hope the readers will be able to use this function in their script properly after practicing the examples of this tutorial.
]]>