How to take log of only non-zero values in dataframe and replace O's with NA's?

Viewed 6409

How do i take log of non-zero values in dataframe and replace 0's with NA's.

I have dataframe like below:

     time                 y1  y2
0    2017-08-06 00:52:00   0   10
1    2017-08-06 00:52:10   1   20
2    2017-08-06 00:52:20   2   0
3    2017-08-06 00:52:30   3   0
4    2017-08-06 00:52:40   0   5
5    2017-08-06 00:52:50   4   6
6    2017-08-06 00:53:00   6   11
7    2017-08-06 00:53:10   7   12
8    2017-08-06 00:53:20   8   0
9    2017-08-06 00:53:30   0   13

I want to take log of all columns expect first column time and log should be calculate of only non-zero values and zero's should be replace with NA's? How do i do this?

So, I tried to do something like this:

cols = df.columns.difference(['time'])
# Replacing O's with NA's using below:

df[cols] = df[cols].mask(np.isclose(df[cols].values, 0), np.nan)

df[cols] = np.log(df[cols]) # but this will try take log of NA's also.

Please help.

Output should be dataframe with same time column, and all the zero's replaced with NA's and log equivalent of the remaining values of all columns expect 1st column.

1 Answers
Related