saltuklev
saltuklev

Reputation: 85

Temporary zeros to nans

      Values     Offset    Result
a1    1.05       2.00   
a2    2.98       1.00           
a3    1.01       nan  
a4    0.02       3.00
a5    0.01       2.00
a6    2.11       1.00
a7    0.08       nan
a8    3.18       nan
a9    2.61       nan
...
..
.

I have a df similar to above. I have a custom function doing negative dynamic offseting for the values. Before applying that func, I am filling nans with 0 then converting the column to int for proper slicing.

df['Offset'] = df['Offset'].fillna(0)
df['Offset'] = df['Offset'].astype(int)

After that I am running my custom func which is doing the job. But nans in the offset column becomes 0 so I want 0's back to nans like originally before? I tried like below:

buffer = np.where(np.isnan(df['Offset']))

this gave me the index locations of previous nans but I don't know how to implement? (convert 0's to nans like original) Thank you,

Upvotes: 0

Views: 74

Answers (2)

rhug123
rhug123

Reputation: 8778

I believe this will work as well

df.loc[df['Offset'] == 0,'Offset'] = np.nan

Edit for if lines have 0 naturally

indexfilter = df.loc[df['Offset'].isna()].index #Use this before fill NaN with 0

Apply normal function, then do below to convert back to NaN.

df.loc[df['Offset'].index.isin(indexfilter),'Offset'] = np.nan

Upvotes: 1

BENY
BENY

Reputation: 323366

You need leave a mask there

m = df.isnull()
df['Offset'] = df['Offset'].fillna(0)
df['Offset'] = df['Offset'].astype(int)
df = df.mask(m)

Upvotes: 2

Related Questions