Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to replace alphabetic values to another column pandas python

I got the following df

housenumber housenumber_extra
1
2 a
55a a
55-4 -4
3455 C

How can i get the following df

housenumber housenumber_extra
1
2 A
55 A
55 -4
3455 C

I filtered the alphabetic values from it with replace function. And then using the update function but its not working. Does someone know a better way

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

housenumber = df['huisnummer'].str.replace('[^a-zA-Z.,-/]', '')

df.set_index('serial', inplace=True)
df.update(huisnummer)
df.reset_index(inplace=True)  # to recover the initial structure

>Solution :

Use .str.extract:

df['housenumber_extra'] = df['housenumber'].str.extract(r'\d+([^\d].+)$')[0].str.strip().fillna(df['housenumber_extra']).str.upper()

Output:

>>> df
  housenumber housenumber_extra
0           1               NaN
1           2                 A
2         55a                 A
3        55-4                -4
4      3455 C                 C
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading