Skip to content Skip to sidebar Skip to footer

Python Replace Non Digit Character In A Dataframe

I have the following dataframe column >>> df2['Age] 1 25 2 35 3 48 y 4 34 yea 5 29 ... I just want to keep the number en replace the value in df2['Age] li

Solution 1:

Use \D+ for replace non numeric to empty string:

df2.Age.replace('\D+','',regex=True,inplace=True)
print (df2)
  Age
125235348434529

Solution 2:

Using str.extract

Ex:

import pandas as pd

df = pd.DataFrame({"Age": ['25', '35', '48 y', '34 yea', '29']})
df["Age"] = df["Age"].str.extract(r"(\d+)", expand=False)
print(df)

Output:

  Age
0  25
1  35
2  48
3  34
4  29

Post a Comment for "Python Replace Non Digit Character In A Dataframe"