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

Python – extract a text from string after the initial extraction of the number

My little school project gets a bit more complicated hence I am looking for a help. I have a data from with some text in Col1 that I use to extract the max numeric value. Now, I have been trying to use that extracted number to extract with any characters before and after it (from space for pre-fix and until space for suffix).

Here is my code:

from numpy import floor, int64
from numpy.core import numeric
import pandas as pd

data = [['aaa', 10], ['nick12 text 1 a 1000a', 15], ['juli078 aq 199 299-01 aaa', 14]]

df = pd.DataFrame(data, columns = ['col1', 'col2'])
print(df.dtypes)

pat = (r'(\d+(?:\.\d+)?)')
df['Number'] = df['col1'].str.extractall(pat).astype(int).max(level=0)
df['Number'] = df['Number'].fillna(0)
df['Number'] = df['Number'].astype(int)

print(df.dtypes)
print(df)

I want to add another column NumberText so my final result looks like this:

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

                        col1  col2  Number NumberText
0                        aaa    10       0  
1      nick12 text 1 a 1000a    15    1000  1000a
2  juli078 aq 199 299-01 aaa    14     299  299-01

>Solution :

You can try:

df['NumberText'] = df.apply(lambda x: ' '.join([word if str(x['Number']) in word else '' for word in x['col1'].split(' ')]).strip(), axis=1)

Output:

                        col1  col2  Number NumberText
0                        aaa    10       0           
1      nick12 text 1 a 1000a    15    1000      1000a
2  juli078 aq 199 299-01 aaa    14     299     299-01
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