How to extract only substring contains kg, g, lb values from the dataframe?

Viewed 28

#input df = {fruits : ['Apple 12kg Fresh', '13g Orange, 'Fresh berries 1g, 'strawberry', 'kiwi 3.2lb' ]}

#desire output: fruits 12kg 13g 1g nan 3.2lb

1 Answers

You can use str.extract like this:

df = pd.DataFrame({"fruits": ['Apple 12kg Fresh', '13g Orange', 'Fresh berries 1g', 'strawberry', 'kiwi 3.2lb']})
(df.fruits.str.extract(r"(\d+\.?\d*\s*(?:kg|g|lb))", expand=False)
 .rename("fruits"))
0     12kg
1      13g
2       1g
3      NaN
4    3.2lb
Name: fruits, dtype: object

Thanks to the R answer that wrote the first version of this regex before me.

If you need the numbers and units, use two separate capture groups to get the number and unit in separate columns, where you can convert to a numeric column type.

Related