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 winsorizing - Pandas, numpy, and scipy

Imports


In [2]:
import pandas as pd                      # pandas for handling mixed data sets 
import numpy as np                       # numpy for basic math and matrix operations
from scipy.stats.mstats import winsorize # scipy for stats and more advanced calculations

Create sample data set


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

scratch_df


Out[3]:
x1
0 729
1 555
2 760
3 493
4 995
5 530
6 281
7 948
8 66
9 989
10 563
11 192
12 156
13 531
14 2
15 996
16 730
17 914
18 265
19 20

Winsorize


In [6]:
scratch_df['x1_winsor'] = winsorize(scratch_df['x1'], limits=[0.1, 0.1])
scratch_df


Out[6]:
x1 x1_winsor
0 729 729
1 555 555
2 760 760
3 493 493
4 995 989
5 530 530
6 281 281
7 948 948
8 66 66
9 989 989
10 563 563
11 192 192
12 156 156
13 531 531
14 2 66
15 996 989
16 730 730
17 914 914
18 265 265
19 20 66