Splitting at underscore in python and storing the first value

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.
Submitted by Pranit Sharma, on August 07, 2022

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.

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 code 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'],

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

# Display DataFrames

# 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)


Example: Splitting at underscore

Python Pandas Programs »


Top MCQs

Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.