Skip to content
Advertisement

Replace multiple “less than values” in different columns in pandas dataframe

I am working with python and pandas. I have a dataset of lab analysis where I am dealing with multiple parameters and detection limits(dl). Many of the samples are reported as below the dl (e.g.<dl,<4)

For example:

JavaScript

My goal is to replace all <dl with dl/2 as a float value.

I can do this for one column pretty easily.

JavaScript

but this requires me looking at the dl and inputting it.

I would like to streamline it to apply it across all variables with one or more detection limits per variable as I have many variables and the detection limit will not always be constant from data frame to data frame this is applied to.

I found something similar in R but not sure how to apply it in python. Any solutions would be appreciated.

Update

So the

JavaScript

works well with dataframe with just columns with numbers. I assume that is a limitation of the eval function. For some reason I can get the code to work on smaller dataframes but after I concatenate them the code will not work on the larger dataframe and I get this error message:

JavaScript

Advertisement

Answer

Use replace instead str.replace than eval all expressions:

JavaScript

1 will be replace by the first capture group .*

Update

Alternative:

JavaScript

Output:

JavaScript

Update

Alternative using melt to flatten your dataframe and pivot to reshape to your original dataframe:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement