How can I use qcut function with a rolling series ? If I do:
def my_func(values):
res = pd.qcut(values, 2)
return res
s = pd.Series([1, 2, -0.1, -8.45, 10, 11, 2, 3])
z = s.rolling(2).apply(my_func)
I obtain:
TypeError: must be real number, not Categorical
as qcut returns a Categorical object.
EDIT1: I would like an output like:
z =
[(0.999, 1.5], (1.5, 2.0]]
[(0.95, 2.0], (-0.101, 0.95]]
[(-4.275, -0.1], (-8.451, -4.275]]
[(-8.451, 0.775], (0.775, 10.0]]
[(9.999, 10.5], (10.5, 11.0]]
[(6.5, 11.0], (1.999, 6.5]]
[(1.999, 2.5], (2.5, 3.0]]
One possible hack solution:
L = []
def my_func(values):
res = pd.qcut(values, 2)
#create lists
L.append(list(res))
#return some aggreagtion for working custom function
return values.sum()
s = pd.Series([1, 2, -0.1, -8.45, 10, 11, 2, 3])
z = s.rolling(2).apply(my_func)
print (z)
print (L)
[[Interval(0.999, 1.5, closed='right'),
Interval(1.5, 2.0, closed='right')],
[Interval(0.94999999999999996, 2.0, closed='right'),
Interval(-0.10100000000000001, 0.94999999999999996, closed='right')],
[Interval(-4.2750000000000004, -0.10000000000000001, closed='right'),
Interval(-8.4509999999999987, -4.2750000000000004, closed='right')],
[Interval(-8.4509999999999987, 0.77500000000000002, closed='right'),
Interval(0.77500000000000002, 10.0, closed='right')],
[Interval(9.9990000000000006, 10.5, closed='right'),
Interval(10.5, 11.0, closed='right')],
[Interval(6.5, 11.0, closed='right'),
Interval(1.9990000000000001, 6.5, closed='right')],
[Interval(1.9990000000000001, 2.5, closed='right'),
Interval(2.5, 3.0, closed='right')]]
Would this work?
def my_func(values):
res = pd.qcut(values, 2, labels=False)[-1]
return res
s = pd.Series([1, 2, -0.1, -8.45, 10, 11, 2, 3])
z = s.rolling(2).apply(my_func)
z
result:
0 NaN
1 1.0
2 0.0
3 0.0
4 1.0
5 1.0
6 0.0
7 1.0
dtype: float64
Just read over your preferred output. I missed it on first read.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.