I have 2 data frames of equal number of columns and rows (NxM). I'm looking to calculate fold change element-wise. So as to each element in data frame 2 gets subtracted with the corresponding element in data frame 1 and divided by the corresponding element in data frame 1. I'm leaving 2 example data frames below with only 2 columns but my data frames have 150 columns and 1000 rows. I'm having trouble writing code for it.
Col 1. | Col 2. |
---|---|
1. | 3. |
4. | 5. |
7. | 1. |
1. | 9. |
Col 1. | Col 2. |
---|---|
1. | 3. |
4. | 5. |
1. | 5. |
7. | 1. |
This is what ive been doing to subtract them:
#bootstrapping all columns
df_sub1 = data1.sample( axis='rows', n=1000, replace = True, ignore_index = True)
df_sub7 = data7.sample( axis='rows', n=1000, replace = True, ignore_index = True)
#subtracting data frames element-wise
df_fc = df_sub7.sub(df_sub1)
How could I go about turning this snippet into fold change for each element? Thank you!
CodePudding user response:
element wise division between two dataframes can be expressed as df1 / df2
. note however, that pandas will attempt to align the indexes. this is not an issue if the dataframes are identically indexed.
using the sample data provided.
df1 = pd.DataFrame({
'c1': [1,4,7,1],
'c2': [3,5,1,9]
})
df2 = pd.DataFrame({
'c1': [1,4,1,7],
'c2': [3,5,5,1]
})
folded = (df2 - df1) / df1
# alternatively:
folded = df2.sub(df1).div(df1)
folded has the following values
c1 c2
0 0.000000 0.000000
1 0.000000 0.000000
2 -0.857143 4.000000
3 6.000000 -0.888889