4.5 Cleaning / filling missing data

pandas objects are equipped with various data manipulation methods for dealing with missing data.

4.5.1 Filling missing values: fillna

The fillna function can “fill in” NA values with non-null data in a couple of ways, which we illustrate:

Replace NA with a scalar value

In [1]: df2
Out[1]: 
        one       two     three four  five  timestamp
a       NaN  0.400157  0.978738  bar  True        NaT
c       NaN  1.867558 -0.977278  bar  True        NaT
e  0.950088 -0.151357 -0.103219  bar  True 2012-01-01
f  0.410599  0.144044  1.454274  bar  True 2012-01-01
h       NaN  0.121675  0.443863  bar  True        NaT

In [2]: df2.fillna(0)
Out[2]: 
        one       two     three four  five  timestamp
a  0.000000  0.400157  0.978738  bar  True 1970-01-01
c  0.000000  1.867558 -0.977278  bar  True 1970-01-01
e  0.950088 -0.151357 -0.103219  bar  True 2012-01-01
f  0.410599  0.144044  1.454274  bar  True 2012-01-01
h  0.000000  0.121675  0.443863  bar  True 1970-01-01

In [3]: df2['four'].fillna('missing')
Out[3]: 
a    bar
c    bar
e    bar
f    bar
h    bar
Name: four, dtype: object

Fill gaps forward or backward

Using the same filling arguments as reindexing, we can propagate non-null values forward or backward:

In [4]: df
Out[4]: 
        one       two     three
a       NaN  0.400157  0.978738
c       NaN  1.867558 -0.977278
e  0.950088 -0.151357 -0.103219
f  0.410599  0.144044  1.454274
h       NaN  0.121675  0.443863

In [5]: df.fillna(method='pad')
Out[5]: 
        one       two     three
a       NaN  0.400157  0.978738
c       NaN  1.867558 -0.977278
e  0.950088 -0.151357 -0.103219
f  0.410599  0.144044  1.454274
h  0.410599  0.121675  0.443863

Limit the amount of filling

If we only want consecutive gaps filled up to a certain number of data points, we can use the limit keyword:

In [6]: df
Out[6]: 
   one       two     three
a  NaN  0.400157  0.978738
c  NaN  1.867558 -0.977278
e  NaN       NaN       NaN
f  NaN       NaN       NaN
h  NaN  0.121675  0.443863

In [7]: df.fillna(method='pad', limit=1)
Out[7]: 
   one       two     three
a  NaN  0.400157  0.978738
c  NaN  1.867558 -0.977278
e  NaN  1.867558 -0.977278
f  NaN       NaN       NaN
h  NaN  0.121675  0.443863

To remind you, these are the available filling methods:

Method Action
pad / ffill Fill values forward
bfill / backfill Fill values backward

With time series data, using pad/ffill is extremely common so that the “last known value” is available at every time point.

The ffill() function is equivalent to fillna(method='ffill') and bfill() is equivalent to fillna(method='bfill')

4.5.2 Filling with a PandasObject

New in version 0.12.

You can also fillna using a dict or Series that is alignable. The labels of the dict or index of the Series must match the columns of the frame you wish to fill. The use case of this is to fill a DataFrame with the mean of that column.

In [8]: dff = pd.DataFrame(np.random.randn(10,3), columns=list('ABC'))

In [9]: dff.iloc[3:5,0] = np.nan

In [10]: dff.iloc[4:6,1] = np.nan

In [11]: dff.iloc[5:8,2] = np.nan

In [12]: dff
Out[12]: 
          A         B         C
0  0.333674  1.494079 -0.205158
1  0.313068 -0.854096 -2.552990
2  0.653619  0.864436 -0.742165
3       NaN -1.454366  0.045759
4       NaN       NaN  1.469359
5  0.154947       NaN       NaN
6 -1.980796 -0.347912       NaN
7  1.230291  1.202380       NaN
8 -0.302303 -1.048553 -1.420018
9 -1.706270  1.950775 -0.509652

In [13]: dff.fillna(dff.mean())
Out[13]: 
          A         B         C
0  0.333674  1.494079 -0.205158
1  0.313068 -0.854096 -2.552990
2  0.653619  0.864436 -0.742165
3 -0.162971 -1.454366  0.045759
4 -0.162971  0.225843  1.469359
5  0.154947  0.225843 -0.559267
6 -1.980796 -0.347912 -0.559267
7  1.230291  1.202380 -0.559267
8 -0.302303 -1.048553 -1.420018
9 -1.706270  1.950775 -0.509652

In [14]: dff.fillna(dff.mean()['B':'C'])
Out[14]: 
          A         B         C
0  0.333674  1.494079 -0.205158
1  0.313068 -0.854096 -2.552990
2  0.653619  0.864436 -0.742165
3       NaN -1.454366  0.045759
4       NaN  0.225843  1.469359
5  0.154947  0.225843 -0.559267
6 -1.980796 -0.347912 -0.559267
7  1.230291  1.202380 -0.559267
8 -0.302303 -1.048553 -1.420018
9 -1.706270  1.950775 -0.509652

New in version 0.13.

Same result as above, but is aligning the ‘fill’ value which is a Series in this case.

In [15]: dff.where(pd.notnull(dff), dff.mean(), axis='columns')
Out[15]: 
          A         B         C
0  0.333674  1.494079 -0.205158
1  0.313068 -0.854096 -2.552990
2  0.653619  0.864436 -0.742165
3 -0.162971 -1.454366  0.045759
4 -0.162971  0.225843  1.469359
5  0.154947  0.225843 -0.559267
6 -1.980796 -0.347912 -0.559267
7  1.230291  1.202380 -0.559267
8 -0.302303 -1.048553 -1.420018
9 -1.706270  1.950775 -0.509652

4.5.3 Dropping axis labels with missing data: dropna

You may wish to simply exclude labels from a data set which refer to missing data. To do this, use the dropna method:

In [16]: df
Out[16]: 
   one       two     three
a  NaN  0.400157  0.978738
c  NaN  1.867558 -0.977278
e  NaN  0.000000  0.000000
f  NaN  0.000000  0.000000
h  NaN  0.121675  0.443863

In [17]: df.dropna(axis=0)
Out[17]: 
Empty DataFrame
Columns: [one, two, three]
Index: []

In [18]: df.dropna(axis=1)
Out[18]: 
        two     three
a  0.400157  0.978738
c  1.867558 -0.977278
e  0.000000  0.000000
f  0.000000  0.000000
h  0.121675  0.443863

In [19]: df['one'].dropna()
Out[19]: Series([], Name: one, dtype: float64)

Series.dropna is a simpler method as it only has one axis to consider. DataFrame.dropna has considerably more options than Series.dropna, which can be examined in the API.

4.5.4 Interpolation

New in version 0.13.0: interpolate(), and interpolate() have revamped interpolation methods and functionality.

New in version 0.17.0: The limit_direction keyword argument was added.

Both Series and Dataframe objects have an interpolate method that, by default, performs linear interpolation at missing datapoints.

In [20]: ts
Out[20]: 
2000-01-31    0.469112
2000-02-29         NaN
2000-03-31         NaN
2000-04-28         NaN
2000-05-31         NaN
2000-06-30         NaN
2000-07-31         NaN
                ...   
2007-10-31   -3.305259
2007-11-30   -5.485119
2007-12-31   -6.854968
2008-01-31   -7.809176
2008-02-29   -6.346480
2008-03-31   -8.089641
2008-04-30   -8.916232
Freq: BM, dtype: float64

In [21]: ts.count()
Out[21]: 61

In [22]: ts.interpolate().count()
Out[22]: 100

In [23]: ts.interpolate().plot()
Out[23]: <matplotlib.axes._subplots.AxesSubplot at 0x2b35ace1edd0>
../_images/series_interpolate.png

Index aware interpolation is available via the method keyword:

In [24]: ts2
Out[24]: 
2000-01-31    0.469112
2000-02-29         NaN
2002-07-31   -5.689738
2005-01-31         NaN
2008-04-30   -8.916232
dtype: float64

In [25]: ts2.interpolate()
Out[25]: 
2000-01-31    0.469112
2000-02-29   -2.610313
2002-07-31   -5.689738
2005-01-31   -7.302985
2008-04-30   -8.916232
dtype: float64

In [26]: ts2.interpolate(method='time')
Out[26]: 
2000-01-31    0.469112
2000-02-29    0.273272
2002-07-31   -5.689738
2005-01-31   -7.095568
2008-04-30   -8.916232
dtype: float64

For a floating-point index, use method='values':

In [27]: ser
Out[27]: 
0.0      0.0
1.0      NaN
10.0    10.0
dtype: float64

In [28]: ser.interpolate()
Out[28]: 
0.0      0.0
1.0      5.0
10.0    10.0
dtype: float64

In [29]: ser.interpolate(method='values')
Out[29]: 
0.0      0.0
1.0      1.0
10.0    10.0
dtype: float64

You can also interpolate with a DataFrame:

In [30]: df = pd.DataFrame({'A': [1, 2.1, np.nan, 4.7, 5.6, 6.8],
   ....:                    'B': [.25, np.nan, np.nan, 4, 12.2, 14.4]})
   ....: 

In [31]: df
Out[31]: 
     A      B
0  1.0   0.25
1  2.1    NaN
2  NaN    NaN
3  4.7   4.00
4  5.6  12.20
5  6.8  14.40

In [32]: df.interpolate()
Out[32]: 
     A      B
0  1.0   0.25
1  2.1   1.50
2  3.4   2.75
3  4.7   4.00
4  5.6  12.20
5  6.8  14.40

The method argument gives access to fancier interpolation methods. If you have scipy installed, you can set pass the name of a 1-d interpolation routine to method. You’ll want to consult the full scipy interpolation documentation and reference guide for details. The appropriate interpolation method will depend on the type of data you are working with.

  • If you are dealing with a time series that is growing at an increasing rate, method='quadratic' may be appropriate.
  • If you have values approximating a cumulative distribution function, then method='pchip' should work well.
  • To fill missing values with goal of smooth plotting, use method='akima'.

Warning

These methods require scipy.

In [33]: df.interpolate(method='barycentric')
Out[33]: 
      A       B
0  1.00   0.250
1  2.10  -7.660
2  3.53  -4.515
3  4.70   4.000
4  5.60  12.200
5  6.80  14.400

In [34]: df.interpolate(method='pchip')
Out[34]: 
         A          B
0  1.00000   0.250000
1  2.10000   0.672808
2  3.43454   1.928950
3  4.70000   4.000000
4  5.60000  12.200000
5  6.80000  14.400000

In [35]: df.interpolate(method='akima')
Out[35]: 
          A          B
0  1.000000   0.250000
1  2.100000  -0.873316
2  3.406667   0.320034
3  4.700000   4.000000
4  5.600000  12.200000
5  6.800000  14.400000

When interpolating via a polynomial or spline approximation, you must also specify the degree or order of the approximation:

In [36]: df.interpolate(method='spline', order=2)
Out[36]: 
          A          B
0  1.000000   0.250000
1  2.100000  -0.428598
2  3.404545   1.206900
3  4.700000   4.000000
4  5.600000  12.200000
5  6.800000  14.400000

In [37]: df.interpolate(method='polynomial', order=2)
Out[37]: 
          A          B
0  1.000000   0.250000
1  2.100000  -4.161538
2  3.547059  -2.911538
3  4.700000   4.000000
4  5.600000  12.200000
5  6.800000  14.400000

Compare several methods:

In [38]: np.random.seed(2)

In [39]: ser = pd.Series(np.arange(1, 10.1, .25)**2 + np.random.randn(37))

In [40]: bad = np.array([4, 13, 14, 15, 16, 17, 18, 20, 29])

In [41]: ser[bad] = np.nan

In [42]: methods = ['linear', 'quadratic', 'cubic']

In [43]: df = pd.DataFrame({m: ser.interpolate(method=m) for m in methods})

In [44]: df.plot()
Out[44]: <matplotlib.axes._subplots.AxesSubplot at 0x2b35ba9dc490>
../_images/compare_interpolations.png

Another use case is interpolation at new values. Suppose you have 100 observations from some distribution. And let’s suppose that you’re particularly interested in what’s happening around the middle. You can mix pandas’ reindex and interpolate methods to interpolate at the new values.

In [45]: ser = pd.Series(np.sort(np.random.uniform(size=100)))

# interpolate at new_index
In [46]: new_index = ser.index | pd.Index([49.25, 49.5, 49.75, 50.25, 50.5, 50.75])

In [47]: interp_s = ser.reindex(new_index).interpolate(method='pchip')

In [48]: interp_s[49:51]
Out[48]: 
49.00    0.471410
49.25    0.476841
49.50    0.481780
49.75    0.485998
50.00    0.489266
50.25    0.491814
50.50    0.493995
50.75    0.495763
51.00    0.497074
dtype: float64

4.5.4.1 Interpolation Limits

Like other pandas fill methods, interpolate accepts a limit keyword argument. Use this argument to limit the number of consecutive interpolations, keeping NaN values for interpolations that are too far from the last valid observation:

In [49]: ser = pd.Series([np.nan, np.nan, 5, np.nan, np.nan, np.nan, 13])

In [50]: ser.interpolate(limit=2)
Out[50]: 
0     NaN
1     NaN
2     5.0
3     7.0
4     9.0
5     NaN
6    13.0
dtype: float64

By default, limit applies in a forward direction, so that only NaN values after a non-NaN value can be filled. If you provide 'backward' or 'both' for the limit_direction keyword argument, you can fill NaN values before non-NaN values, or both before and after non-NaN values, respectively:

In [51]: ser.interpolate(limit=1)  # limit_direction == 'forward'
Out[51]: 
0     NaN
1     NaN
2     5.0
3     7.0
4     NaN
5     NaN
6    13.0
dtype: float64

In [52]: ser.interpolate(limit=1, limit_direction='backward')
Out[52]: 
0     NaN
1     5.0
2     5.0
3     NaN
4     NaN
5    11.0
6    13.0
dtype: float64

In [53]: ser.interpolate(limit=1, limit_direction='both')
Out[53]: 
0     NaN
1     5.0
2     5.0
3     7.0
4     NaN
5    11.0
6    13.0
dtype: float64

4.5.5 Replacing Generic Values

Often times we want to replace arbitrary values with other values. New in v0.8 is the replace method in Series/DataFrame that provides an efficient yet flexible way to perform such replacements.

For a Series, you can replace a single value or a list of values by another value:

In [54]: ser = pd.Series([0., 1., 2., 3., 4.])

In [55]: ser.replace(0, 5)
Out[55]: 
0    5.0
1    1.0
2    2.0
3    3.0
4    4.0
dtype: float64

You can replace a list of values by a list of other values:

In [56]: ser.replace([0, 1, 2, 3, 4], [4, 3, 2, 1, 0])
Out[56]: 
0    4.0
1    3.0
2    2.0
3    1.0
4    0.0
dtype: float64

You can also specify a mapping dict:

In [57]: ser.replace({0: 10, 1: 100})
Out[57]: 
0     10.0
1    100.0
2      2.0
3      3.0
4      4.0
dtype: float64

For a DataFrame, you can specify individual values by column:

In [58]: df = pd.DataFrame({'a': [0, 1, 2, 3, 4], 'b': [5, 6, 7, 8, 9]})

In [59]: df.replace({'a': 0, 'b': 5}, 100)
Out[59]: 
     a    b
0  100  100
1    1    6
2    2    7
3    3    8
4    4    9

Instead of replacing with specified values, you can treat all given values as missing and interpolate over them:

In [60]: ser.replace([1, 2, 3], method='pad')
Out[60]: 
0    0.0
1    0.0
2    0.0
3    0.0
4    4.0
dtype: float64

4.5.6 String/Regular Expression Replacement

Note

Python strings prefixed with the r character such as r'hello world' are so-called “raw” strings. They have different semantics regarding backslashes than strings without this prefix. Backslashes in raw strings will be interpreted as an escaped backslash, e.g., r'\' == '\\'. You should read about them if this is unclear.

Replace the ‘.’ with nan (str -> str)

In [61]: d = {'a': list(range(4)), 'b': list('ab..'), 'c': ['a', 'b', np.nan, 'd']}

In [62]: df = pd.DataFrame(d)

In [63]: df.replace('.', np.nan)
Out[63]: 
   a    b    c
0  0    a    a
1  1    b    b
2  2  NaN  NaN
3  3  NaN    d

Now do it with a regular expression that removes surrounding whitespace (regex -> regex)

In [64]: df.replace(r'\s*\.\s*', np.nan, regex=True)
Out[64]: 
   a    b    c
0  0    a    a
1  1    b    b
2  2  NaN  NaN
3  3  NaN    d

Replace a few different values (list -> list)

In [65]: df.replace(['a', '.'], ['b', np.nan])
Out[65]: 
   a    b    c
0  0    b    b
1  1    b    b
2  2  NaN  NaN
3  3  NaN    d

list of regex -> list of regex

In [66]: df.replace([r'\.', r'(a)'], ['dot', '\1stuff'], regex=True)
Out[66]: 
   a       b       c
0  0  stuff  stuff
1  1       b       b
2  2     dot     NaN
3  3     dot       d

Only search in column 'b' (dict -> dict)

In [67]: df.replace({'b': '.'}, {'b': np.nan})
Out[67]: 
   a    b    c
0  0    a    a
1  1    b    b
2  2  NaN  NaN
3  3  NaN    d

Same as the previous example, but use a regular expression for searching instead (dict of regex -> dict)

In [68]: df.replace({'b': r'\s*\.\s*'}, {'b': np.nan}, regex=True)
Out[68]: 
   a    b    c
0  0    a    a
1  1    b    b
2  2  NaN  NaN
3  3  NaN    d

You can pass nested dictionaries of regular expressions that use regex=True

In [69]: df.replace({'b': {'b': r''}}, regex=True)
Out[69]: 
   a  b    c
0  0  a    a
1  1       b
2  2  .  NaN
3  3  .    d

or you can pass the nested dictionary like so

In [70]: df.replace(regex={'b': {r'\s*\.\s*': np.nan}})
Out[70]: 
   a    b    c
0  0    a    a
1  1    b    b
2  2  NaN  NaN
3  3  NaN    d

You can also use the group of a regular expression match when replacing (dict of regex -> dict of regex), this works for lists as well

In [71]: df.replace({'b': r'\s*(\.)\s*'}, {'b': r'\1ty'}, regex=True)
Out[71]: 
   a    b    c
0  0    a    a
1  1    b    b
2  2  .ty  NaN
3  3  .ty    d

You can pass a list of regular expressions, of which those that match will be replaced with a scalar (list of regex -> regex)

In [72]: df.replace([r'\s*\.\s*', r'a|b'], np.nan, regex=True)
Out[72]: 
   a   b    c
0  0 NaN  NaN
1  1 NaN  NaN
2  2 NaN  NaN
3  3 NaN    d

All of the regular expression examples can also be passed with the to_replace argument as the regex argument. In this case the value argument must be passed explicitly by name or regex must be a nested dictionary. The previous example, in this case, would then be

In [73]: df.replace(regex=[r'\s*\.\s*', r'a|b'], value=np.nan)
Out[73]: 
   a   b    c
0  0 NaN  NaN
1  1 NaN  NaN
2  2 NaN  NaN
3  3 NaN    d

This can be convenient if you do not want to pass regex=True every time you want to use a regular expression.

Note

Anywhere in the above replace examples that you see a regular expression a compiled regular expression is valid as well.

4.5.7 Numeric Replacement

Similar to DataFrame.fillna

In [74]: df = pd.DataFrame(np.random.randn(10, 2))

In [75]: df[np.random.rand(df.shape[0]) > 0.5] = 1.5

In [76]: df.replace(1.5, np.nan)
Out[76]: 
          0         1
0 -0.844214 -1.021415
1  0.432396 -0.323580
2  0.423825  0.799180
3  1.262614  0.751965
4       NaN       NaN
5       NaN       NaN
6 -0.498174 -1.060799
7  0.591667 -0.183257
8  1.019855 -1.482465
9       NaN       NaN

Replacing more than one value via lists works as well

In [77]: df00 = df.values[0, 0]

In [78]: df.replace([1.5, df00], [np.nan, 'a'])
Out[78]: 
          0         1
0         a -1.021415
1  0.432396 -0.323580
2  0.423825  0.799180
3   1.26261  0.751965
4       NaN       NaN
5       NaN       NaN
6 -0.498174 -1.060799
7  0.591667 -0.183257
8   1.01985 -1.482465
9       NaN       NaN

In [79]: df[1].dtype
Out[79]: dtype('float64')

You can also operate on the DataFrame in place

In [80]: df.replace(1.5, np.nan, inplace=True)

Warning

When replacing multiple bool or datetime64 objects, the first argument to replace (to_replace) must match the type of the value being replaced type. For example,

s = pd.Series([True, False, True])
s.replace({'a string': 'new value', True: False})  # raises

TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str'

will raise a TypeError because one of the dict keys is not of the correct type for replacement.

However, when replacing a single object such as,

In [81]: s = pd.Series([True, False, True])

In [82]: s.replace('a string', 'another string')
Out[82]: 
0     True
1    False
2     True
dtype: bool

the original NDFrame object will be returned untouched. We’re working on unifying this API, but for backwards compatibility reasons we cannot break the latter behavior. See :issue:`6354` for more details.