Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas Series.str.split() function

Pandas Series.str.split() function

Pandas Common Functions Common Pandas functions


Series.str.split() is a function in Pandas used to split strings.

During data processing, we often need to split a string into multiple parts, such as splitting a sentence into words or comma-separated values into a list.split() The function splits strings into multiple parts according to a specified delimiter.

Word meaning:split means "to separate or split", indicating dividing a string into multiple parts.


Basic syntax and parameters

str.split() is a string accessor method of Series, so you need a Series containing strings first, and then call it through the .str accessor.

Syntax format



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

Parameter Description

Parameters Type Required Description Default value
pat str Optional The delimiter, which can be a string or a regular expression. Defaults to whitespace. None (whitespace)
n int Optional The number of splits. -1 means no limit, splitting into as many parts as possible. -1
expand bool Optional Whether to expand the result into a DataFrame. Defaults to False (returns a Series of lists). False

Function description


Example

Let us thoroughly master str.split() through a series of examples from simple to complex.

Example 1: Basic Usage - Splitting by Whitespace

Example

import

pandas

as

pd

Create a Series containing sentences

s

=

pd.

Series

(

[

'hello world'

,

'runoob python'

,

'pandas data analysis'

]

)

Split by whitespace (default behavior)

result

=

s.

str

.

split

(

)

print

(

"Original Series:"

)

print

(

s

)

print

(

"nSplit result:"

)

print

(

result

)

Output result:



原始 Series:

0         hello world

1      runoob python

2    pandas data analysis

dtype: object



Split results:

0         [hello, world]

1    [runoob, python]

2    [pandas, data, analysis]

Code analysis:

  1. s.str.split() Strings are split by whitespace (spaces, tabs, etc.) by default.
  2. Returns a Series containing lists, each holding the split substrings.
  3. 'pandas data analysis' is split into three parts.

Example 2: Splitting by a Specified Delimiter

can be used via pat The parameter specifies a custom delimiter.

Example

import

pandas

as

pd

Create a Series with comma-separated values

s

=

pd.

Series

(

[

'apple,banana,orange'

,

'dog,cat,bird'

,

'red,green,blue'

]

)

Split by comma

result

=

s.

str

.

split

(

','

)

print

(

"Original Series:"

)

print

(

s

)

print

(

"nResult after splitting by comma:"

)

print

(

result

)

Output result:



原始 Series:

0    apple,banana,orange

1       dog,cat,bird

2       red,green,blue

dtype: object



Split results:

0    [apple, banana, orange]

1       [dog, cat, bird]

2       [red, green, blue]

Code analysis:

Example 3: Limiting the Number of Splits

Pass n The parameter can limit the number of splits.

Example

import

pandas

as

pd

s

=

pd.

Series

(

[

'a,b,c,d,e'

,

'1,2,3,4,5'

]

)

Limit to 2 parts

result_2

=

s.

str

.

split

(

','

,

n

=

2

)

Limit to 1 part (i.e., split only once)

result_1

=

s.

str

.

split

(

','

,

n

=

1

)

print

(

"Original Series:"

)

print

(

s

)

print

(

"nLimited to 2 parts:"

)

print

(

result_2

)

print

(

"nLimited to 1 part:"

)

print

(

result_1

)

Output result:



原始 Series:

0       a,b,c,d,e

1       1,2,3,4,5

dtype: object



Limit split into 2 parts:

0       [a, b, c,d,e]

1       [1, 2, 3,4,5]



Limit split into 1 part:

0            [a, b,c,d,e]

1            [1, 2,3,4,5]

Code analysis:

Example 4: Expanding into a DataFrame

When expand=True , the split result is expanded into a DataFrame.

Example

import

pandas

as

pd

Create a Series with comma-separated values

s

=

pd.

Series

(

[

'apple,banana,orange'

,

'dog,cat,bird'

,

'red,green,blue'

]

)

Expand into a DataFrame

result

=

s.

str

.

split

(

','

,

expand

=

True

)

print

(

"Original Series:"

)

print

(

s

)

print

(

"nExpanded into a DataFrame:"

)

print

(

result

)

print

(

"nDataFrame type:"

,

type

(

result

)

)

Output result:



原始 Series:

0    apple,banana,orange

1       dog,cat,bird

2       red,green,blue

dtype: object



展开为 DataFrame:

        0       1       2

0   apple   banana  orange

1     dog     cat    bird

2     red   green    blue



DataFrame 类型: 

Code analysis:

Example 5: Splitting with a Regular Expression

split() It also supports using a regular expression as the delimiter.

Example

import

pandas

as

pd

Create a Series with different delimiters

s

=

pd.

Series

(

[

'hello-world'

,

'runoob_python'

,

'pandas#tutorial'

]

)

Split by regular expression (matching any of -, _, #)

result

=

s.

str

.

split

(

r

'[-_#]'

)

print

(

"Original Series:"

)

print

(

s

)

print

(

"nSplit by regular expression:"

)

print

(

result

)

Output result:



原始 Series:

0     hello-world

1   runoob_python

2    pandas#tutorial

dtype: object



Split by regular expression:

0       [hello, world]

1       [runoob, python]

2    [pandas, tutorial]

Code analysis:

Example 6: Working with Real Data

In practical applications,split() is often used in combination with other functions.

Example

import

pandas

as

pd

Simulate data extracted from logs

logs

=

pd.

Series

(

[

   

'2024-01-01 10:30:45 ERROR Connection failed'

,

   

'2024-01-01 10:31:12 INFO User logged in'

,

   

'2024-01-01 10:32:00 WARNING Memory usage high'

]

)

Split the log content

log_parts

=

logs.

str

.

split

(

r

's+'

,

expand

=

True

)

print

(

"Original log:"

)

print

(

logs

)

print

(

"nSplit DataFrame:"

)

print

(

log_parts

)

Rename columns

log_parts.

columns

=

[

'timestamp'

,

'level'

,

'message'

]

print

(

"nResult after renaming:"

)

print

(

log_parts

)

Output result:



Raw log:

0    2024-01-01 10:30:45 ERROR Connection failed

1    2024-01-01 10:31:12 INFO User logged in

2    2024-01-01 10:32:00 WARNING Memory usage high

dtype: object



拆分后的 DataFrame:

                  0     1     2

0  2024-01-01 10:30:45  ERROR  Connection failed

1  2024-01-01 10:31:12   INFO  User logged in

2  2024-01-01 10:32:00  WARNING  Memory usage high



Renamed result:

               timestamp    level                message

0  2024-01-01 10:30:45    ERROR    Connection failed

1  2024-01-01 10:31:12     INFO      User logged in

2  2024-01-01 10:32:00  WARNING  Memory usage high

Code analysis:


Notes


Pandas Common Functions Common Pandas functions