pythonpandas

Python/Pandas - Breaking postal code into postal and extension


I have a following column in pandas dataframe which has postal code -

postal code
56789-2345
45675
null
23445-445
1234-45
34567

I need to break it into postal code and ext like below -

Postal code     postal_ext
56789           2345
45675
null
23445           445
1234            45
34567

How can i do this


Solution

  • Try with split

    out = df['postal code'].str.split('-',expand=True)
    out.columns = ['Postal code','postal_ext']
    
    out
      Postal code postal_ext
    0       56789       2345
    1       45675       None
    2         NaN        NaN
    3       23445        445
    4        1234         45
    5       34567       None