📜  Python| Pandas Series.str.rpartition()(1)

📅  最后修改于: 2023-12-03 15:04:22.050000             🧑  作者: Mango

Python | Pandas Series.str.rpartition()

Introduction

In Python, Pandas is a powerful library for data manipulation and analysis. The Series.str.rpartition() method in Pandas is used to split the strings in a Series into three parts using a specified separator. This method returns a DataFrame with three columns, namely 'before', 'separator', and 'after', which contain the respective parts obtained from splitting.

Syntax
Series.str.rpartition(sep)
Parameters
  • sep (string): The separator used to split the strings in the Series.
Returns

The Series.str.rpartition() method returns a DataFrame with three columns: 'before', 'separator', and 'after'.

Example

Consider a Series with string values:

import pandas as pd

data = pd.Series(['apple_mango_banana', 'cat_dog_elephant', 'car_bike_train'])

Applying Series.str.rpartition('_') on this Series will split the strings into three parts based on underscore '_':

result = data.str.rpartition('_')
print(result)

Output:

           before separator     after
0           apple         _  mango_banana
1             cat         _     dog_elephant
2             car         _     bike_train

As seen in the above example, the original string values are split into three parts: 'before', 'separator', and 'after', which are stored as separate columns in the resulting DataFrame.

Note: If the separator is not found in a particular string, the 'before' column will contain the whole string, and the 'separator' and 'after' columns will be empty.

Conclusion

The Series.str.rpartition() method in Pandas is a useful tool to split strings in a Series into three parts based on a specified separator. It returns a DataFrame with three columns containing the resulting parts. This method can be helpful in various data manipulation and analysis tasks.