编写Python程序以分隔一系列字母和数字并将其转换为数据框

假设您有一个序列以及将字母和数字分开的结果,并将其存储在数据框中,

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

为了解决这个问题,我们将遵循以下方法,

解决方案

  • 定义一个系列。

  • Apple系列内部的提取方法使用正则表达式模式将字母和数字分开,然后将其存储在数据框中-

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

例子

让我们看一下下面的实现以获得更好的理解-

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)

输出

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

猜你喜欢