search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to
chevron_leftSeries Cookbook
Appending values to a SeriesApplying a function to SeriesBinning values in a SeriesChanging data type of SeriesChecking if a value is NaN in Pandas SeriesChecking if all values are NaN in SeriesChecking if all values in a Series are uniqueChecking if Series has missing valuesConverting Python list to SeriesConverting Series of lists into DataFrameConverting Series to a Numpy arrayConverting Series to Python listCounting frequency of values in SeriesCreating a Series of zeroesCreating a Series with constant valueFiltering strings based on length in SeriesFiltering values of a SeriesGetting frequency counts of values in intervalsGetting index of largest valueGetting index of smallest valueGetting index of value in SeriesGetting integer index of largest valueGetting integer index of smallest valueGetting integer index of value in SeriesGetting intersection of SeriesGetting length of each string in SeriesGetting list of integer indices where value is boolean True in SeriesGetting the index of the nth value in SeriesGetting the most frequent value in SeriesGetting value of Series using integer indexGrouping Series by its valuesHandling error - "Truth value of a Series is ambiguous"Inverting a Series of booleansRemoving missing values from a SeriesRemoving substrings from strings in a SeriesRemoving values from SeriesResetting index of SeriesSorting values in a SeriesSplitting strings based on spaceStripping leading and trailing whitespaceTaking the floor or ceiling of values in SeriesUsing index.get_loc(~) for multiple values
check_circle
Mark as learned
thumb_up
1
thumb_down
0
chat_bubble_outline
0
Comment
auto_stories Bi-column layout
settings

Splitting strings based on space in Pandas DataFrame

schedule Aug 10, 2023
Last updated
local_offer
PythonPandas
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

Solution

To split strings based on space in Pandas, use the Series.str.split(~) method.

Examples

Basic solution

Consider the following Pandas DataFrame:

import pandas as pd
df = pd.DataFrame({'A':['i love python', 'hello world']})
df
A
0 i love python
1 hello world

To split the strings in column A by space:

df_split = df['A'].str.split(' ', expand=True)
df_split
0 1 2
0 i love python
1 hello world None

Note the following:

  • None is returned for the third column for the second string because there are only two tokens (hello and world)

  • expand=True returns a DataFrame where each cell contains the split token - the default expand=False returns a DataFrame:

    df['A'].str.split(' ') # expand=False
    0 [i, love, python]
    1 [hello, world]
    Name: A, dtype: object

To concatenate the initial DataFrame with the new DataFrame created by split(~), use Pandas' concat(~) method:

pd.concat([df, df_split], axis=1)
A 0 1 2
0 i love python i love python
1 hello world hello world None

Here, axis=1 means we wish to concatenate the DataFrames horizontally.

Splitting string based on the first occurrence of a space

Consider the same DataFrame as before:

df = pd.DataFrame({'A':['i love python', 'hello world']})
df
A
0 i love python
1 hello world

To split based on the first occurrence of a space, set n=1 like so:

df['A'].str.split(' ', n=1, expand=True)
0 1
0 i love python
1 hello world
robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
1
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!