Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pandas extracting numbers within text to a new column

I have the following text in column A:

A   
hellothere_3.43  
hellothere_3.9

I would like to extract only the numbers to another new column B (next to A), e.g:

B                      
3.43   
3.9

I use: str.extract('(\d.\d\d)', expand=True) but this copies only the 3.43 (i.e. the exact number of digits). Is there a way to make it more generic?

Many thanks!

like image 375
MGs Avatar asked Dec 18 '25 23:12

MGs


1 Answers

Use Regex.

Ex:

import pandas as pd

df = pd.DataFrame({"A": ["hellothere_3.43", "hellothere_3.9"]})
df["B"] = df["A"].str.extract("(\d*\.?\d+)", expand=True)
print(df)

Output:

                 A     B
0  hellothere_3.43  3.43
1   hellothere_3.9   3.9
like image 81
Rakesh Avatar answered Dec 20 '25 19:12

Rakesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!