Found 10476 Articles for Python

How to combine multiple graphs in Python

Kiran P
Updated on 10-Nov-2020 05:28:29

19K+ Views

IntroductionMatplotlib allows to add more than one plot in the same graph. In this tutorial, I will show you how to present data in the same plot, on two different axes.How to do it..1. Install matplotlib by opening up the python command prompt and firing pip install matplotlib.import matplotlib.pyplot as plt2. Prepare the data to be displayed.import matplotlib.pyplot as plt # data prep (I made up data no accuracy in these stats) mobile = ['Iphone', 'Galaxy', 'Pixel'] # Data for the mobile units sold for 4 Quaters in Million units_sold = (('2016', 12, 8, 6), ('2017', 14, 10, ... Read More

How to match text at the start or end of a string in Python?

Kiran P
Updated on 10-Nov-2020 05:24:29

945 Views

Problem..Assume you need to check the start or end of a string for a specific text patterns. The common patterns might be filename extensions but can also be anything. I will show you few methods on how you can do this.Startswith() methodA simple way to check the beginning of a string is by using startswith() method.Exampletext = "Is USA colder than Australia?" print(f"output {text.startswith('Is')}")OutputTrueExamplefilename = "Hello_world.txt" print(f"output {filename.startswith('Hello')}")OutputTrueExamplesite_url = 'https://www.something.com' print(f"output {site_url.startswith('http:')}")OutputFalseExampleprint(f"output {site_url.startswith('https:')}")OutputTrueendswith() Method.A simple way to check the ending of a string is by using endswith() method.Outputtext = "Is USA colder than Australia?" print(f"output ... Read More

How to Search and Replace text in Python?

Kiran P
Updated on 10-Nov-2020 05:22:42

703 Views

ProblemYou want to search for and replace a text pattern in a string.If we have a very simple literal patterns, using the str.replace() method is an optimal solution.Exampledef sample(): yield 'Is' yield 'USA' yield 'Colder' yield 'Than' yield 'Canada?' text = ' '.join(sample()) print(f"Output {text}")OutputIs USA Colder Than Canada?Let us first see how to search a text.# search for exact text print(f"Output {text == 'USA'}")OutputFalseWe can search for the text using the basic string methods, such as str.find(), str.endswith(), str.startswith().# text start with print(f"Output {text.startswith('Is')}")OutputTrue# text ends with print(f"Output {text.startswith('Is')}")OutputTrue# search text with find print(f"Output ... Read More

How to Implement Priority Queue in Python?

Kiran P
Updated on 10-Nov-2020 05:20:13

512 Views

Introduction...The queue module provides a first-in, first-out (FIFO), Last-in, First out (LIFO) data structure suitable for multi-threaded programming. Queues can be used to pass data or any wide range of information e.g. session details, paths, variables, .. between creator and consumer threads safely. Locking is generally handled for the caller.Note : This discussion assumes you already understand the general nature of a queue. If you do not, you may want to read some of the references before continuing.1. Let us implement a basic FIFO Queue.import queue fifo = queue.Queue() # put numbers into queue for i in range(5): fifo.put(i) ... Read More

How to improve file reading performance in Python with MMAP function?

Kiran P
Updated on 09-Nov-2020 11:02:12

763 Views

Introduction..MMAP abbreviated as memory mapping when mapped to a file uses the operating systems virtual memory to access the data on the file system directly, instead of accessing the data with the normal I/O functions. There by improving the I/O performance as it does not require either making a separate system call for each access or copying data between buffers.To a matter of fact anything in memory for instance a SQLlite database when created in-memeory has better performance compared to on disk.Memory-mapped files can be treated as mutable strings or file-like objects, depending on what you want to do.MMAP supports ... Read More

How to read text files using LINECACHE in Python

Kiran P
Updated on 09-Nov-2020 10:59:40

574 Views

Solution..The linecache module implements cache which holds the contents of files, parsed into separate lines, in memory. linecache module returns line/s by indexing into a list, and saves time over repeatedly reading the file and parsing lines to find the one desired.lincecache module is very useful when looking for multiple lines from the same file.Prepare test data. You can get this text by just using Google and searching for sample text.Lorem ipsum dolor sit amet, causae apeirian ea his, duo cu congue prodesset. Ut epicuri invenire duo, novum ridens eu has, in natum meliore noluisse sea. Has ei stet explicari. ... Read More

How to compare files in Python

Kiran P
Updated on 09-Nov-2020 10:57:07

9K+ Views

Problem.You need to compare files in Python.Solution..The filecmp module in python can be used to compare files and directories. 1.cmp(file1, file2[, shallow])filecmp Compares the files file1 and file2 and returns True if identical, False if not. By default, files that have identical attributes as returned by os.stat() are considered to be equal. If shallow is not provided (or is True), files that have the same stat signature are considered equal.cmpfiles(dir1, dir2, common[, shallow])Compares the contents of the files contained in the list common in the two directories dir1 and dir2. cmpfiles returns a tuple containing three lists - match, mismatch, ... Read More

How to scrape through Media Files in Python?

Kiran P
Updated on 09-Nov-2020 10:53:30

154 Views

IntroductionIn a real world corporate business setting, most data may not be stored in text or Excel files. SQL-based relational databases such as Oracle, SQL Server, PostgreSQL, and MySQL are in wide use, and many alternative databases have become quite popular.The choice of database is usually dependent on the performance, data integrity, and scalability needs of an application.How to do it..In this example we will how to create a sqlite3 database. sqllite is installed by default with python installation and doesn't require any further installations. If you are unsure please try below. We will also import Pandas.Loading data from SQL ... Read More

Program to find start indices of all anagrams of a string S in T in Python

Arnab Chakraborty
Updated on 09-Nov-2020 10:51:25

258 Views

Suppose we have two strings S and T, we have to find all the start indices of S's anagrams in T. The strings consist of lowercase letters only and the length of both strings S and T will not be larger than 20 and 100.So, if the input is like S = "cab" T = "bcabxabc", then the output will be [0, 1, 5, ], as the substrings "bca", "cab" and "abc".To solve this, we will follow these steps:Define a map m, n := size of s, set left := 0, right := 0, counter := size of pdefine an ... Read More

How to select the largest of each group in Python Pandas DataFrame?

Kiran P
Updated on 09-Nov-2020 10:49:32

664 Views

IntroductionOne of the most basic and common operations to perform during data analysis is to select rows containing the largest value of some columns within a group. In this post, I will show you how to find the largest of each group within a DataFrame.Problem..Let us understand the task first, assume you are given a movies dataset and requested to list the most popular film of each year based on popularity.How to do it..1.Preparing the data.Well Google is full of datasets. I often use kaggle.com to get the datasets I need for my data analysis. Feel free to login to ... Read More

Advertisements