Home > Backend Development > Python Tutorial > How to Split a Pandas DataFrame String Column into Two Using `.str.split()`?

How to Split a Pandas DataFrame String Column into Two Using `.str.split()`?

Susan Sarandon
Release: 2024-12-29 20:05:13
Original
425 people have browsed it

How to Split a Pandas DataFrame String Column into Two Using `.str.split()`?

How to Split a Dataframe String Column into Two Columns

In this scenario, the dataframe df contains a single string column named 'row' and the goal is to split it into two new string columns: 'fips' and 'row'.

To accomplish this, the .str.split() method can be employed. This method enables splitting a string on a specified delimiter (in this case, a known separator like a space) and returning a Series of lists.

df[['fips', 'row']] = df['row'].str.split(' ', n=1, expand=True)
Copy after login

Here's a breakdown of how each parameter in the above code functions:

  • ' ': The space character acts as the delimiter, indicating where to split the string.
  • n=1: This parameter limits the split to only one occurrence of the delimiter, ensuring that the string is divided into two parts.
  • expand=True: By default, .str.split() returns a Series of lists. However, expand=True instructs it to further split each list into individual columns.

The result is a dataframe with three columns: 'fips', 'row', and the original 'row' column still intact.

This method effectively splits the 'row' column based on the space delimiter and creates two additional columns, 'fips' and 'row', containing the respective parts of the split string.

The above is the detailed content of How to Split a Pandas DataFrame String Column into Two Using `.str.split()`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template