Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Programming Articles
Page 30 of 2547
Find the k most frequent words from data set in Python
If there is a need to find the k most frequent words in a data set, Python can help us achieve this using the collections module. The collections module has a Counter class which counts the frequency of words after we supply a list of words to it. We also use the most_common() method to find the specified number of most frequent words. Basic Approach Using Counter In the below example we take a paragraph, create a list of words using split(), then apply Counter() to count word frequencies. Finally, most_common() returns the top k most frequent words ...
Read MoreFind all the numbers in a string using regular expression in Python
Extracting numbers from text is a common requirement in Python data analytics. Regular expressions provide a powerful way to define patterns for matching digits, decimal numbers, and numbers with signs. Basic Number Extraction The re.findall() function extracts all occurrences of a pattern from a string. The pattern r'\d+' matches one or more consecutive digits ? import re text = "Go to 13.8 miles and then -4.112 miles." numbers = re.findall(r'\d+', text) print(numbers) ['13', '8', '4', '112'] Note that this pattern extracts only digits, splitting decimal numbers and ignoring signs. ...
Read MoreCount frequencies of all elements in array in Python using collections module
Python lists allow duplicate elements, so we often need to count how many times each element appears. The frequency of elements indicates how many times an element occurs in a list. The Counter class from the collections module provides an efficient way to count element frequencies. Syntax Counter(iterable) Where iterable is any Python iterable like a list, tuple, or string. Basic Example The Counter() function returns a dictionary-like object with elements as keys and their counts as values − from collections import Counter days = ['Mon', 'Tue', 'Wed', 'Mon', 'Mon', ...
Read MoreCount distinct elements in an array in Python
In Python lists, we often encounter duplicate elements. While len() gives us the total count including duplicates, we sometimes need to count only the distinct (unique) elements. Python provides several approaches to accomplish this task. Using Counter from collections The Counter class from the collections module creates a dictionary where elements are keys and their frequencies are values. We can use its keys() method to get distinct elements ? from collections import Counter days = ['Mon', 'Tue', 'Wed', 'Mon', 'Tue'] print("Length of original list:", len(days)) distinct_elements = Counter(days).keys() print("List with distinct elements:", list(distinct_elements)) print("Length ...
Read MoreBackward iteration in Python
Sometimes we need to iterate through a list in reverse order − reading the last element first, then the second-to-last, and so on. Python provides three common approaches: range() with negative step, slice notation [::-1], and the reversed() built-in function. Using range() with Negative Step Start from the last index and step backwards by -1 until index 0 ? days = ['Mon', 'Tue', 'Wed', 'Thu'] for i in range(len(days) - 1, -1, -1): print(days[i]) Thu Wed Tue Mon range(3, -1, -1) generates indices 3, 2, 1, ...
Read Moreappend() and extend() in Python
The append() and extend() methods both add elements to a Python list, but they behave differently. append() adds its argument as a single element (even if it's a list), while extend() adds each element of an iterable individually. append() Adds the argument as one element to the end of the list. List length increases by exactly 1, regardless of the argument type. days = ['Mon', 'Tue', 'Wed'] print("Original:", days) # Append a single element days.append('Thu') print("After append('Thu'):", days) # Append a list — added as a nested list days.append(['Fri', 'Sat']) print("After append(['Fri', 'Sat']):", days) ...
Read MoreAdd a row at top in pandas DataFrame
Adding a row at the top of a Pandas DataFrame is a common operation when you need to insert headers, summary rows, or new data at the beginning. There are several methods to achieve this − using pd.concat(), loc[] with index manipulation, or iloc slicing. Create a Sample DataFrame import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['Delhi', 'Mumbai', 'Pune'] }) print("Original DataFrame:") print(df) Original DataFrame: Name ...
Read MoreAbsolute and Relative frequency in Pandas
In statistics, frequency indicates how many times a value appears in a dataset. Absolute frequency is the raw count, while relative frequency is the proportion (count divided by total observations). Pandas provides built-in methods for calculating both. Absolute Frequency Using value_counts() The simplest way to count occurrences of each value ? import pandas as pd data = ["Chandigarh", "Hyderabad", "Pune", "Pune", "Chandigarh", "Pune"] df = pd.Series(data).value_counts() print(df) Pune 3 Chandigarh 2 Hyderabad 1 dtype: int64 ...
Read MoreAbsolute Deviation and Absolute Mean Deviation using NumPy
In statistics, data variability measures how dispersed values are in a sample. Two key measures are Absolute Deviation (difference of each value from the mean) and Mean Absolute Deviation (MAD) (average of all absolute deviations). NumPy provides efficient functions to calculate both. Formulas $$\mathrm{Absolute\:Deviation_i = |x_i - \bar{x}|}$$ $$\mathrm{MAD = \frac{1}{n}\sum_{i=1}^{n}|x_i - \bar{x}|}$$ Where xi is each data point, x̄ is the mean, and n is the sample size. Absolute Deviation Calculate the absolute deviation for each element in a data sample ? from numpy import mean, absolute data = [12, ...
Read MoreA += B Assignment Riddle in Python
The += operator on a mutable object inside a tuple creates a surprising Python riddle − the operation succeeds (the list gets modified) but also raises a TypeError because tuples don't support item assignment. Both things happen simultaneously. The Riddle Define a tuple with a list as one of its elements, then try to extend the list using += ? tupl = (5, 7, 9, [1, 4]) tupl[3] += [6, 8] Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment ...
Read More