Splitting at underscore in python and storing the first value

Given a Pandas DataFrame with column names having underscores in their names By Pranit Sharma Last updated : September 26, 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.

A string is a group of characters. A string may contain any type of character including numerical characters, alphabetical characters, special characters, etc. Splitting a string means the distribution of string in two or more parts.

Problem statement

Given a Pandas DataFrame with column names having underscores in their names, we need to split all the column values with the underscore and store the first elements in another column.

Splitting at underscore and storing the first value

By default, a string is split with a space between two words but if we want to split a string with any other character, we need to pass the specific character inside the str.split() method. Here, for splitting a string into two different columns, we are going to use str.split() method.

In the below example, we will split a string with an underscore (_), and for this purpose, we will pass this character inside the split() method.

Let us understand with the help of an example,

Python program to split at underscore in python and storing the first value

# Importing pandas package
import pandas as pd

# Creating two dictionary
d = {
    'Name':['Ram_Sharma', 'Shyam_rawat','Seeta_phoghat','Geeta_phogat'],
    'Age':[20,32,33,19]
}

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

# Display DataFrames
print("DataFrame1:\n",df,"\n")

# Splitting the column name and storing 
# the first part into another column
df['First_Name'] = df['Name'].str.split('_').str[0]

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

Output

The output of the above program is:

Example: Splitting at underscore

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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