How to select rows that do not start with some str in pandas?

Given a pandas dataframe, we have to select rows that do not start with some str in pandas. By Pranit Sharma Last updated : October 05, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

The string is a group of characters, these characters may consist of all the lower case, upper case, and special characters present on the keyboard of a computer system. A string is a data type and the number of characters in a string is known as the length of the string.

Problem statement

Suppose we are given a data frame with some string columns and we need to select rows that values that do not start with some string.

Selecting rows that do not start with some str in pandas

For this purpose, we can use the string accessor to get string functionality. The get Method can grab a given index of the string and we can pass the specific sub-string with which we have to compare and to reverse the result we will use the tilde sign(~).

Let us understand with the help of an example,

Python program to select rows that do not start with some str in pandas

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {'col':['Harry','Carry','Darry','Jerry']}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display DataFrame
print("Original DataFrame:\n",df,"\n")

# Filtering rows
res = df[~df.col.str.get(0).isin(['H', 'J'])]

# Display result
print("Result:\n",df)

Output

The output of the above program is:

Example: How to select rows that do not start with some str in pandas?

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.