Thursday, 1 February 2024

Pandas: Filter Dataframe rows using startswith method

'startswith' method can be applied on a DataFrame column to check whether particular value starts with given string or not.

 

Example

name_starts_with_k = df['Name'].str.lower().str.startswith('k')
persons_name_starts_with_k = df[name_starts_with_k]

 

The startswith() method is applied to the 'Name' column with the substring 'k'. It returns a Boolean Series where True indicates that the string in that particular column starts with the specified substring 'k', else False.

 

startswith.py
import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'kranthi', 'Jitendra', "Kumar"],
        'Age': [34, 35, 234, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Hobbies': ['Football,Cricket', 'Tennis, cricket', 'Trekking, reading books', 'Chess', 'Read Books', 'Cricket']}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

# Get a boolean series to find the names starts with k (case insensitive)
name_starts_with_k = df['Name'].str.lower().str.startswith('k')
print('\nname_starts_with_k\n', name_starts_with_k)

persons_name_starts_with_k = df[name_starts_with_k]
print('\npersons_name_starts_with_k\n', persons_name_starts_with_k)

 

Output

Original DataFrame
       Name  Age       City                  Hobbies
0   Krishna   34  Bangalore         Football,Cricket
1     Sailu   35  Hyderabad          Tennis, cricket
2      Joel  234  Hyderabad  Trekking, reading books
3   kranthi   35    Chennai                    Chess
4  Jitendra   52  Bangalore               Read Books
5     Kumar   34    Chennai                  Cricket

name_starts_with_k
 0     True
1    False
2    False
3     True
4    False
5     True
Name: Name, dtype: bool

persons_name_starts_with_k
       Name  Age       City           Hobbies
0  Krishna   34  Bangalore  Football,Cricket
3  kranthi   35    Chennai             Chess
5    Kumar   34    Chennai           Cricket

 

 

Previous                                                 Next                                                 Home

Pandas: Filter Dataframe rows using contains method

Using contains() method, we can filter the data frame rows based on given sub string presences.

 

Example 1: Filter rows when the column value contain given substring.

book_in_hobbies = df['Hobbies'].str.lower().str.contains('book')
persons_hobby_contain_book = df[book_in_hobbies]

We can achieve the case insensitive search by setting the argument case to False while calling contains method.

 

book_in_hobbies = df['Hobbies'].str.contains('book', case=False)

Example 2: Check for substring in multiple columns

contains_c = df[['Name', 'City', 'Hobbies']].apply(lambda x: x.str.contains('c', case=False))

We applied contains() method to multiple columns 'Name', 'City', 'Hobbies' using the apply() method. It returns a DataFrame where each cell contains a Boolean value indicating whether the corresponding element contains the substring 'c' or not.

 

Find the below working application.

 

contains.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Krishna"],
        'Age': [34, 35, 234, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Hobbies': ['Football,Cricket', 'Tennis, cricket', 'Trekking, reading books', 'Chess', 'Read Books', 'Cricket']}
df = pd.DataFrame(data)

print('Original DataFrame')
print(df)

# Convert the column values to lower case to perform the case insensitive search
book_in_hobbies = df['Hobbies'].str.lower().str.contains('book')
persons_hobby_contain_book = df[book_in_hobbies]

print('\nBoolean series to find the people whose hobby contain the string "book"\n', book_in_hobbies)
print('\nPeople whose hobby contains the string "book"\n',persons_hobby_contain_book)

book_in_hobbies = df['Hobbies'].str.contains('book', case=False)
persons_hobby_contain_book = df[book_in_hobbies]
print('\nBoolean series to find the people whose hobby contain the string "book"\n', book_in_hobbies)
print('\nPeople whose hobby contains the string "book"\n',persons_hobby_contain_book)

# Check for substring in multiple columns
contains_c = df[['Name', 'City', 'Hobbies']].apply(lambda x: x.str.contains('c', case=False))
print('\nRow that contains the character "c" case insensitive : \n', contains_c)

Output

Original DataFrame
       Name  Age       City                  Hobbies
0   Krishna   34  Bangalore         Football,Cricket
1     Sailu   35  Hyderabad          Tennis, cricket
2      Joel  234  Hyderabad  Trekking, reading books
3     Chamu   35    Chennai                    Chess
4  Jitendra   52  Bangalore               Read Books
5   Krishna   34    Chennai                  Cricket

Boolean series to find the people whose hobby contain the string "book"
 0    False
1    False
2     True
3    False
4     True
5    False
Name: Hobbies, dtype: bool

People whose hobby contains the string "book"
        Name  Age       City                  Hobbies
2      Joel  234  Hyderabad  Trekking, reading books
4  Jitendra   52  Bangalore               Read Books

Boolean series to find the people whose hobby contain the string "book"
 0    False
1    False
2     True
3    False
4     True
5    False
Name: Hobbies, dtype: bool

People whose hobby contains the string "book"
        Name  Age       City                  Hobbies
2      Joel  234  Hyderabad  Trekking, reading books
4  Jitendra   52  Bangalore               Read Books

Row that contains the character "c" case insensitive : 
     Name   City  Hobbies
0  False  False     True
1  False  False     True
2  False  False    False
3   True   True     True
4  False  False    False
5  False   True     True

 

 

Previous                                                 Next                                                 Home

Check for existence of key in a dictionary using in operator in Python

Using the ‘in’ operator in ‘if’ condition, we can check for the existenace of a key in Python Dictionary.

employee = {'id' : 123, 'name' : 'krishna', 'age' : 34}

if 'id' in employee:
    print('id is in employee')
else:
    print('id is not in employee')

Above snippet defines a dictionary named employee with three key-value pairs representing employee information: 'id' with a value of 123, 'name' with a value of 'krishna', and 'age' with a value of 34.

 

Subsequently, an if statement checks whether the key 'id' exists in the dictionary. If the key is present, it prints 'id is in employee'; otherwise, it prints 'id is not in employee'. In this case, since 'id' is indeed a key in the dictionary, the condition evaluates to True, and the first print statement is executed, displaying 'id is in employee' as the output.

 

Find the below working application.

check_for_key_existence.py

employee = {'id' : 123, 'name' : 'krishna', 'age' : 34}

if 'id' in employee:
    print('id is in employee')
else:
    print('id is not in employee')

if 'city' in employee:
    print('city is in employee')
else:
    print('city is not in employee')

Output

id is in employee
city is not in employee


Previous                                                 Next                                                 Home

Convert BGR image to a different color space

cv2.cvtColor is used for color space conversions on OpenCV. This method is helpful, when you want to analyze or manipulate images in different color spaces.

Signature

cv2.cvtColor(src, code, dst)

 

Following table summarizes the parameters of cvtColor method.

Parameter

Description

src

Source image that we want to convert

code

Color space conversion code.

Ex: cv2.COLOR_BGR2RGB, cv2.COLOR_BGR2GRAY

dst

It is an optional parameter, specifies the destination image where the converted image will be stored. If not provided, OpenCV will create an output image for you.

 

Example 1: Convert the BGR image to Gray

bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

 

Example 2: Convert BGR image to RGB

bgr_to_rgb = cv.cvtColor(image, cv.COLOR_BGR2RGB)

 

Example 3: Convert BGR image to HSV

bgr_to_hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)

 

Find the below working application.

 

bgr_to_other_color_spaces.py

import cv2 as cv

# Read the image as matrix of pixels
image = cv.imread('flowers.png')
image = cv.resize(image, (1000, 800))

# Display the image in new window
cv.imshow('Original image', image)

# Convert BGR image to RGB
bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
bgr_to_rgb = cv.cvtColor(image, cv.COLOR_BGR2RGB)
bgr_to_hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)

#bgr_to_bgr555 = cv.cvtColor(image, cv.COLOR_BGR2BGR555)
#bgr_to_bgr565 = cv.cvtColor(image, cv.COLOR_BGR2BGR565)
#bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2YCrCb)
#bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2HLS)
#bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2BGRA)
#bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2HLS_FULL)
#bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2HSV)
#bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2LAB)
#bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2LUV)
#bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2XYZ)

cv.imshow('bgr_to_gray', bgr_to_gray)
cv.imshow('bgr_to_rgb', bgr_to_rgb)
cv.imshow('bgr_to_hsv', bgr_to_hsv)

# Wait for Infinite amount of time for a keyboard key to be pressed
cv.waitKey(0)

# Close the OpenCV windows
cv.destroyAllWindows()

Output

 

Original image


 

 

BGR to Gray



BGR to RGB



BGR to HSV

 


  

Previous                                                    Next                                                    Home

OpenCV uses BGR as default color space

OpenCV use  BGR (Blue, Green, Red) color space as its default color representation for images. But other libraries like Matplotlib use RGB color space (RGB) as default.

What is meant by OpenCV BGR representation?

when you load an image using OpenCV, it's typically stored as a NumPy array with the channels ordered as BGR.

 

image = cv.imread('image.png')

 

For example, when you read an image using OpenCV's cv2.imread function, the result is a NumPy array where the color channels are arranged as BGR format.

 

When you display the same image numpy array in Matplotlib (which use RGB as default color space), Red become blue and blue become red. You can confirm the same from below application.

 

Original image

 


 

default_color_space.py

import cv2 as cv
import matplotlib.pyplot as plt

image = cv.imread('rgb.png')

cv.imshow('image in opencv', image)

plt.imshow(image)
plt.title('Image in matplotlib')
plt.show()

# Close the OpenCV windows
cv.destroyAllWindows()

Output

 

Image in opencv


 


Same image array in Matplotlib.

 

 


Note

When you convert an image from BGR to RGB, the pixel values themselves do not change. If the BGR image has pixel values (1, 2, 3) for a specific pixel, the corresponding RGB image will also have the same pixel values (1, 2, 3) for that pixel. The conversion only involves rearranging the color channels in terms of interpretation.

 

For example, if the BGR image has (1, 2, 3) for a pixel, the equivalent pixel in the RGB image will also be (1, 2, 3).


Previous                                                    Next                                                    Home

Color spaces in image processing

Color space is a mathematical representation used to define various colors in such a way that, these can be understood by computers, video or image processing devices, libraries etc.,

 

Following are the some popular color spaces.

 

a. RGB (Red, Green, Blue) : This color space represents thencolors by mixing different intensities of red, green, and blue light. For example

         1. (255, 0, 0) : represent Red color

         2. (0, 255, 0) : represent Green color

         3. (0, 0, 255) : represent Blue color

         4. (0, 0, 0) : represent balck color

         5. (255, 255, 255) : represent white color etc.,

 

b. HSV (Hue, Saturation, Value): Hue represents the dominant color wavelength. Saturation measures the intensity or vividness of the color. Value represents the brightness of the color. HSV is designed to represent colors in a way that aligns more with how humans perceive color.

 

c. BGR (Blue, Green, Red) : This color space represents thencolors by mixing different intensities of blue, green, and red light. For example

         1. (255, 0, 0) : represent Blue color

         2. (0, 255, 0) : represent Green color

         3. (0, 0, 255) : represent Red color

         4. (0, 0, 0) : represent balck color

         5. (255, 255, 255) : represent white color etc.,

 

d. CMY(K) (Cyan, Magenta, Yellow, Key/Black): It represents colors by specifying the amounts of cyan, magenta, yellow, and optionally black inks needed to reproduce a color.

Previous                                                    Next                                                    Home

Tuesday, 30 January 2024

Looping over the dictionary using items() method in Python

Using items() method, we can iterate over a dictionary.

>>> emp_dict = {'id' : 1, 'name' : 'Krishna', 'age' : 34}
>>> 
>>> for key, value in emp_dict.items():
...   print(f'{key} --> {value}')
... 
id --> 1
name --> Krishna
age --> 34

 

Above code demonstrates how to iterate over a dictionary and print its key-value pairs.

 

emp_dict = {'id' : 1, 'name' : 'Krishna', 'age' : 34}

This line creates a dictionary named emp_dict. A dictionary in Python is a collection of key-value pairs. Here, the dictionary represents an employee with three pieces of information: their 'id' (which is 1), 'name' (which is 'Krishna'), and 'age' (which is 34).

 

for key, value in emp_dict.items():

This line starts a for loop. The .items() method is called on the dictionary emp_dict. This method returns a view object that displays a list of dictionary's (key, value) tuple pairs.

 

In each iteration of the loop, key and value will be assigned to the corresponding pair of items from the dictionary. For instance, in the first iteration, key will be 'id' and value will be 1, in the second iteration, key will be 'name' and value will be 'Krishna', and so on.

 

 

Previous                                                 Next                                                 Home