Python - How to do a left, right, and mid of a string in a pandas dataframe?

Given a Pandas DataFrame, we have to do a left, right, and mid of a string in a pandas dataframe. By Pranit Sharma Last updated : September 29, 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.

Suppose, we have a DataFrame with multiple columns which is of string type, for better understanding and effective analysis, we sometimes use only the left few letters or right few letters of the values, and hence we are going to find an optimized solution to do a left, right and mid of a string.

Let us understand with the help of an example,

Python program to do a left, right, and mid of a string in a pandas dataframe

# Importing pandas package
import pandas as pd

# Creating two dictionaries
d1 = {
    'State':['Punjab','Maharashtra','Rajasthan','Gujrat'],
    'Capital_city':['Chandigarh','Mumbai','Jaipur','Gandhinagar'],
    'City':['Amritsar','Pune','Kota','Surat']
}

# Creating DataFrame
df = pd.DataFrame(d1)

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

# doin left of string
df['left'] = df['State'].str[:2]

# doing right
df['right'] = df['State'].str[:-2]

# doing mid
df['mid'] = df['State'].apply(lambda x: x[len(x)//2:len(x)//2+1])

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

Output

Example: Do a left, right, and mid of a string in a pandas

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






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