How to calculate log2foldchange in python?
2
0
Entering edit mode
3 months ago

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 • 516 views
3
Entering edit mode
3 months ago
Jack Tierney ▴ 320

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.

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

1
Entering edit mode
3 months ago

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.