編寫一個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

更新於:2021年2月24日

133 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告