License


Copyright (C) 2017 J. Patrick Hall, jphall@gwu.edu

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


Simple discretization - Pandas and numpy

Imports


In [2]:
import pandas as pd              # pandas for handling mixed data sets 
import numpy as np               # numpy for basic math and matrix operations

Create sample data set


In [3]:
scratch_df = pd.DataFrame({'x1': pd.Series(np.random.randn(20))}) 

scratch_df


Out[3]:
x1
0 1.314953
1 -1.550305
2 -1.168123
3 0.531124
4 0.089564
5 1.140028
6 -0.633408
7 -0.152805
8 0.608893
9 -2.485712
10 -1.309433
11 1.057359
12 1.920338
13 0.526936
14 0.438425
15 -1.262219
16 1.340732
17 -0.096697
18 -0.596703
19 -0.958907

Discretize


In [5]:
scratch_df['x1_discrete'] = pd.DataFrame(pd.cut(scratch_df['x1'], 5))
scratch_df


Out[5]:
x1 x1_discrete
0 1.314953 (1.0391, 1.92]
1 -1.550305 (-1.605, -0.723]
2 -1.168123 (-1.605, -0.723]
3 0.531124 (0.158, 1.0391]
4 0.089564 (-0.723, 0.158]
5 1.140028 (1.0391, 1.92]
6 -0.633408 (-0.723, 0.158]
7 -0.152805 (-0.723, 0.158]
8 0.608893 (0.158, 1.0391]
9 -2.485712 (-2.49, -1.605]
10 -1.309433 (-1.605, -0.723]
11 1.057359 (1.0391, 1.92]
12 1.920338 (1.0391, 1.92]
13 0.526936 (0.158, 1.0391]
14 0.438425 (0.158, 1.0391]
15 -1.262219 (-1.605, -0.723]
16 1.340732 (1.0391, 1.92]
17 -0.096697 (-0.723, 0.158]
18 -0.596703 (-0.723, 0.158]
19 -0.958907 (-1.605, -0.723]