I have a pandas dataframe (let’s call it df), and one of the columns of this df (let’s say column 10) specifies if a sensor has acquired data (1 it did, 0 it didn’t). In the rows where the sensor acquired data the columns from 11 to 20 are filled with sensor’s data, otherwise they are filled with zeroes.
What I would like to do is to turn the zeroes in columns from 11 to 20 into nans and do that on the basis of column 10 (i.e.: sensor’s acquisition status) to avoid eliminating “true” zeroes measured by the sensor.
I’m struggling on how to do it, though.
0
It’s best to provide an example of your dataframe so that the answer works for you.
The trick it to use .loc
, listing the condition and the columns you would like to change:
import pandas as pd
import numpy as np
df = pd.DataFrame({
"id": [0, 1, 2, 3, 4, 5],
"10": [True, True, True, False, True, False],
"11": [39.5, 0, -34, 0, 0, 0],
"12": [40, 5, 12, 0, 0, 0],
})
df.loc[~df["10"], ["11", "12"]] = np.nan
print(df)
Output:
id 10 11 12
0 0 True 39.5 40.0
1 1 True 0.0 5.0
2 2 True -34.0 12.0
3 3 False NaN NaN
4 4 True 0.0 0.0
5 5 False NaN NaN