Splitting Full Names into First, Middle, Last Names using Pandas - Tech Support Guide
When working with datasets that contain full names, it is often necessary to split them into separate columns for first, middle, and last names. This can be easily achieved using the powerful Pandas library in Python. In this guide, we will walk you through the process of splitting full names using Pandas, particularly focusing on a dataset containing a 'Names' column.
Prerequisites
Before we begin, ensure that you have the following:
- Python installed
- Pandas library installed
- A dataset with a 'Names' column (e.g., an Excel file: names.xlsx)
Step-by-Step Guide
Now, let's start splitting the full names:
import pandas as pd
df = pd.read_excel(r"C:\SAMPLEEXCELFILES
ames.xlsx")
splitted = df['Names'].str.split()
first = splitted.str[0]
middle = splitted.str[1] if splitted.str.len() >= 2 else ''
last = splitted.str[-1]
Explanation:
- Import the Pandas library.
- Load the dataset (Excel file in this case) into the Pandas dataframe.
- Split the 'Names' column using the
.str.split()function, creating a Pandas Series with a list of names. - Extract the first name by indexing the splitted Series with [0].
- Extract the middle name only if the length of the list is greater than or equal to 2 (i.e., at least two names present), otherwise, leave it blank.
- Extract the last name by indexing the splitted Series using negative indexing with [-1].
Creating New Columns
After extracting the names, create new columns in the dataframe to store them:
df['First_Name'] = first
df['Middle_Name'] = middle
df['Last_Name'] = last
In this guide, we've demonstrated the process of splitting full names into separate columns for the first, middle, and last names using the Pandas library in Python. You can use this technique in any data manipulation task requiring the extraction and separation of names from a 'Names' column.
References
- Type: Articles
Title: "The Strings Properties in Pandas"
Link: https://www.pandas.pydata.org/docs/user_guide/text.html#strings-properties - Type: Books
Title: "Python for Data Analysis"
Author: Wes McKinney