Change language

Python | Pandas Split strings into two lists / columns using str.split ()

It works similarly to the default " str.split () can be applied to the entire series. .str must be prefixed every time before calling this method to distinguish it from the default function in Python, otherwise it will throw an error.

Syntax: Series.str.split (pat = None, n = -1, expand = False)

Parameters:

pat: String value, separator or delimiter to separate string at.
n: Numbers of max separations to make in a single string, default is -1 which means all.
expand: Boolean value, returns a data frame with different value in different columns if True. Else it returns a series with list of strings.

Return Type: Series of list or Data frame depending on expand Parameter

To download CSV used in the code, click here.

In the following examples, the data frame used contains details of some NBA players. An image of the data frame before any operations is attached below. 

Example # 1: Splitting a line into list

This data uses the split function to split the "Command" column at each "t". The parameter is set to 1, and therefore the maximum number of splits per line will be 1. The expansion parameter is False, and therefore a series with a list of lines is returned instead of a data frame.

# pandas module import

import pandas as pd

 
# read CSV file from URL

data = pd.read_csv ( " https://media.python.engineering/wp-content/uploads /nba.csv " )

  
# deleting columns null to avoid errors

data.dropna (inplace = True )

 
# new data frame with delimited columns

data [ "Team" ] = data [ " Team " ]. str . Split ( "t" , n = 1 , expand = True )

 
# df display
data

Output:
As shown in the output image, the Team column now has a list. The line was split on the first occurrence of "t" and not on subsequent occurrences because the parameter n was set to 1 (max. 1 split per line). 

Example # 2: Creating separate columns from a string

In this example, the Name column is separated by a space ("") and the extension parameter is set to True, which means it will return a data frame with all the separated rows in different columns. The dataframe is then used to create new columns and the old name column is dropped using the .drop () method.

 

# pandas module import

import pandas as pd

 
# read CSV file from URL

data = pd.read_csv ( " https://media.python.engineering/wp-content/uploads/nba.csv " )

 
# deleting null columns, to avoid errors

data.dropna (inplace  = True )

 
# new data frame with delimited columns

new = data [ " Name " ]. str . split ( "" , n = 1 , expand = True )

 
# create a separate name column from a new dataframe

data [ "First Name" ] = new [ 0 ]

 
# create a separate last name column from a new data frame

data [ " Last Name " ] = new [ 1 ]

 
# Removing old columns Name

data.drop ( columns = [ "Name" ], inplace = True )

 
# df display
data

Output:
As shown in the output image, the split () function returned a new dataframe, and it was used to create two new columns (First Name and Last Name) in the dataframe.

New dataframe

Data frame with added columns

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically