This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How to calculate log2foldchange in python?

Hello,

I am trying to find log2foldchange between 2 numpy arrays and then find standard deviation of log2foldchange. Here is the formula which I am applying

import numpy as np
l2fc = np.log2(np.nan_to_num(np.divide(a, b)))

a and b are example arrays. After applying the formula l2fc array is filled with -inf and inf values. Can anyone please guide me?

numpy python log2foldchange

2 answers

As Matthias answered above, there are likely 0s in your arrays that are turned into Nans by np.divide(). This is because the default replacement for Nan in np.nan_to_num() is 0 and the log2 of 0 returns Inf.

Try this instead:

l2fc = np.log2(np.nan_to_num(np.divide(a, b), nan=1))

The most likely explanation is, that your data contains zeros. This would return Inf, since you can't compute a log value of 0. The typical approach is, that pseudo counts are added prior to calculating the log, e.g. +1.

Log in to answer this question.