Missing desired character in string with a Regex call

Viewed 49

I'm missing a desired character from this string:

df=pd.DataFrame({Score:[1.20\n1\n99%\n6.75\nX\n-\n14\n2\n1%\n+72]})

Desired result:

1.20\n6.75\n14.00

Here is the regex I used:

.str.findall(r'(?m)^\d+\.\d+$').str.join("\n")

This regex is not capturing \n14; I want the result to be \n14.00. In other words the regex must handle the missing float point and inserting the 00 as appropriate. Meaning if this happens across any of the desired values in the list/string. So I'm stuck on finding a solution.

See the current regex result in code below:

import pandas as pd
import re

df=pd.DataFrame({'Score: ['1.20\n1\n99%\n6.75\nX\n-\n14\n2\n1%\n+72']})

df = df['Score'].str.findall(r'(?m)^\d+\.\d+$').str.join("\n")
df
0       1.20\n6.75
Name: Score, dtype: object
1 Answers

Here are a couple of ideas:

  1. You might want to match lines with only float values or with integers that contain at least two digits:
r'(?m)^(?:\d+\.\d+|\d{2,})$'

See the regex demo.

  1. You may extract all lines that only contain float numbers and any amount of digits if the next line also only contains digits:
(?m)^(?:\d+\.\d+|\d+$(?=\n\d+$))$

See this regex demo.

In Pandas, you can use

df=pd.DataFrame({'Score': ['1.20\n1\n99%\n6.75\nX\n-\n14\n2\n1%\n+72']})
df['ID']=df['Score'].str.findall(r'(?m)^(\d+\.\d+|\d{2,})$')
df['ID']=df['ID'].apply(lambda x: "\n".join(map(lambda a: f'{a:.2f}', map(float,x))))
>>> df['ID']
# => 0    1.20\n6.75\n14.00
#    Name: ID, dtype: object
Related