Write a Python program to separate a series of alphabets and digits and convert them to a dataframe

PythonPandasServer Side ProgrammingProgramming

Assume you have a series and the result for separating alphabets and digits and store it in dataframe as,

series is:
0    abx123
1    bcd25
2    cxy30
dtype: object
Dataframe is
   0   1
0 abx 123
1 bcd 25
2 cxy 30

To solve this, we will follow the below approach,

Solution

  • Define a series.

  • Apple series extract method inside use regular expression pattern to separate alphabets and digits then store it in a dataframe −

series.str.extract(r'(\w+[a-z])(\d+)')

Example

Let’s see the below implementation to get a better understanding −

import pandas as pd
series = pd.Series(['abx123', 'bcd25', 'cxy30'])
print("series is:\n",series)
df = series.str.extract(r'(\w+[a-z])(\d+)')
print("Dataframe is\n:" ,df)

Output

series is:
0    abx123
1    bcd25
2    cxy30
dtype: object
Dataframe is
:  0   1
0 abx 123
1 bcd 25
2 cxy 30
raja
Published on 11-Feb-2021 10:44:34
Advertisements