Calculating and placing values in second level column in MultiIndex Pandas DataFrame
I have a multi-indexed DataFrame in which I want to place a second level column named AB. The values of this level two columns should equal AD [1] / DP for each sample, for example. Sample1 AB = 60/180
import pandas as pd
import numpy as np
genotype_data = [
['0/1', '120,60', 180, 5, '0/1', '200,2', 202, 99],
['0/1', '200,20', 60, 99, '0/1', '200,50', 250, 99],
['0/1', '200,2', 202, 99, '0/1', '200,2', 202, 99]
]
genotype_columns = [['Sample1', 'Sample2'], ['GT', 'AD', 'DP', 'GQ']]
cols = pd.MultiIndex.from_product(genotype_columns)
df = pd.DataFrame(data=genotype_data, columns=cols)
This code creates the following input file / df:
Sample1 Sample2
GT AD DP GQ GT AD DP GQ
0/1 120,60 180 5 0/1 200,2 202 99
0/1 200,20 60 3 0/1 200,50 250 99
0/1 200,2 202 99 0/1 200,2 202 99
The desired output should be:
Sample1 Sample2
GT AD DP GQ AB GT AD DP GQ AB
0/1 120,60 180 5 0.33 0/1 200,2 202 99 0.01
0/1 200,20 60 3 0.33 0/1 200,50 250 99 0.20
0/1 200,2 202 99 0.01 0/1 200,2 202 99 0.01
I have come up with a solution for this, but it is rather slow, inefficient and relies on loops. I need a much more efficient solution as I will be doing this on very large files.
def calc_AB(df):
sam = df.columns.levels[0][0]
AD = df.xs('AD', level=1, axis=1).unstack().str.split(",", n=2)
DP = df.xs('DP', level=1, axis=1).unstack()
AB = round(pd.to_numeric(AD.str[1]) / pd.to_numeric(DP), 2)
df[sam, 'AB'] = AB.tolist()
return df
dfs = [calc_AB(df[[sam]].astype(str)) for sam in df.columns.levels[0].tolist()]
pd.concat(dfs, axis=1)
Any help with this would be much appreciated.
+3
source to share
1 answer
You need to reorganize the indexes to make sure there is only one column named "AD":
df.columns = df.columns.swaplevel(0,1)
stacked = df.stack()
# AD DP GQ GT
#0 Sample1 120,60 180 5 0/1
# Sample2 200,2 202 99 0/1
#1 Sample1 200,20 60 99 0/1
# Sample2 200,50 250 99 0/1
#2 Sample1 200,2 202 99 0/1
# Sample2 200,2 202 99 0/1
Calculating a new column is now trivial:
stacked['AB'] = stacked['AD'].str.split(',').str[1].astype(int)/stacked['DP']
stacked
# AD DP GQ GT AB
#0 Sample1 120,60 180 5 0/1 0.333333
# Sample2 200,2 202 99 0/1 0.009901
#1 Sample1 200,20 60 99 0/1 0.333333
# Sample2 200,50 250 99 0/1 0.200000
#2 Sample1 200,2 202 99 0/1 0.009901
# Sample2 200,2 202 99 0/1 0.009901
You can restore the indexes to what they were before if you want.
+2
source to share