pivot table with aggfunc that combines two funtions
pandas, python
Solution
I think you need `lambda` - solution with pandas function `median` + `std` (is necessary change `ddof=0`, because by default `ddof=1` in pandas):
aggfunc=lambda x: x.median() - x.std(ddof=0)
what is same as:
aggfunc=lambda x: np.median(x) - np.std(x)
Sample:
data = pd.DataFrame({
'Genename' : ['a','a','b','b', 'b', 'b'],
'Mediancoverage' : [4, 1, 5, 3, 7, 5],
'Componentnr' : [1,2,1,2,1,2],
})
print (data)
Componentnr Genename Mediancoverage
0 1 a 4
1 2 a 1
2 1 b 5
3 2 b 3
4 1 b 7
5 2 b 5
pivot=pd.pivot_table(data,
columns='Genename',
values='Mediancoverage',
index='Componentnr',
aggfunc=lambda x: x.median() - x.std(ddof=0))
print (pivot)
Genename a b
Componentnr
1 4 5
2 1 3
pivot=pd.pivot_table(data,
columns='Genename',
values='Mediancoverage',
index='Componentnr',
aggfunc=lambda x: np.median(x) - np.std(x))
print (pivot)
Genename a b
Componentnr
1 4 5
2 1 3
Problem
I want to create a pivot table with an aggfunc that combines two functions. I tried this ``` pivot=pd.pivot_table(data, columns='Genename', values=['Mediancoverage'],index='Componentnr', aggfunc=(np.median - np.std)) ``` and got this error: TypeError: unsupported operand type(s) for -: 'function' and 'function' I understand the problem but what is the solution?