I have a series as below,
JavaScript
x
12
12
1
Name id
2
A 1 10
3
2 20
4
3 30
5
. .
6
. .
7
B 1 100
8
2 200
9
3 300
10
.
11
.
12
I wanted to do something below,
JavaScript
1
2
1
pd.cut(series.id * series.value, bins=10)
2
How can I do this in a performant way?
Advertisement
Answer
Combine Series.mul
with Index.get_level_values
:
JavaScript
1
12
12
1
s.mul(s.index.get_level_values('id'))
2
# `get_level_values` works both with "names" (i.e. `id`) and "index" (i.e. `1`)
3
4
Name id
5
A 1 10
6
2 40
7
3 90
8
B 1 100
9
2 400
10
3 900
11
dtype: int64
12
So, you can feed that to pd.cut
, of course:
JavaScript
1
14
14
1
pd.cut(s.mul(s.index.get_level_values('id')), bins=10)
2
3
Name id
4
A 1 (9.11, 99.0]
5
2 (9.11, 99.0]
6
3 (9.11, 99.0]
7
B 1 (99.0, 188.0]
8
2 (366.0, 455.0]
9
3 (811.0, 900.0]
10
dtype: category
11
Categories (10, interval[float64, right]): [(9.11, 99.0] < (99.0, 188.0] < (188.0, 277.0] <
12
(277.0, 366.0] (544.0, 633.0] < (633.0, 722.0] <
13
(722.0, 811.0] < (811.0, 900.0]]
14