pandas 0.7.0 documentation

Working with missing data

In this section, we will discuss missing (also referred to as NA) values in pandas.

Note

The choice of using NaN internally to denote missing data was largely for simplicity and performance reasons. It differs from the MaskedArray approach of, for example, scikits.timeseries. We are hopeful that NumPy will soon be able to provide a native NA type solution (similar to R) performant enough to be used in pandas.

Missing data basics

When / why does data become missing?

Some might quibble over our usage of missing. By “missing” we simply mean null or “not present for whatever reason”. Many data sets simply arrive with missing data, either because it exists and was not collected or it never existed. For example, in a collection of financial time series, some of the time series might start on different dates. Thus, values prior to the start date would generally be marked as missing.

In pandas, one of the most common ways that missing data is introduced into a data set is by reindexing. For example

In [715]: df = DataFrame(randn(5, 3), index=['a', 'c', 'e', 'f', 'h'],
   .....:                columns=['one', 'two', 'three'])

In [716]: df['four'] = 'bar'

In [717]: df['five'] = df['one'] > 0

In [718]: df
Out[718]: 
        one       two     three four   five
a  0.059117  1.138469 -2.400634  bar   True
c -0.280853  0.025653 -1.386071  bar  False
e  0.863937  0.252462  1.500571  bar   True
f  1.053202 -2.338595 -0.374279  bar   True
h -2.359958 -1.157886 -0.551865  bar  False

In [719]: df2 = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])

In [720]: df2
Out[720]: 
        one       two     three four   five
a  0.059117  1.138469 -2.400634  bar   True
b       NaN       NaN       NaN  NaN    NaN
c -0.280853  0.025653 -1.386071  bar  False
d       NaN       NaN       NaN  NaN    NaN
e  0.863937  0.252462  1.500571  bar   True
f  1.053202 -2.338595 -0.374279  bar   True
g       NaN       NaN       NaN  NaN    NaN
h -2.359958 -1.157886 -0.551865  bar  False

Values considered “missing”

As data comes in many shapes and forms, pandas aims to be flexible with regard to handling missing data. While NaN is the default missing value marker for reasons of computational speed and convenience, we need to be able to easily detect this value with data of different types: floating point, integer, boolean, and general object. In many cases, however, the Python None will arise and we wish to also consider that “missing” or “null”. Lastly, for legacy reasons inf and -inf are also considered to be “null” in computations. Since in NumPy divide-by-zero generates inf or -inf and not NaN, I think you will find this is a worthwhile trade-off (Zen of Python: “practicality beats purity”).

To make detecting missing values easier (and across different array dtypes), pandas provides the isnull() and notnull() functions, which are also methods on Series objects:

In [721]: df2['one']
Out[721]: 
a    0.059117
b         NaN
c   -0.280853
d         NaN
e    0.863937
f    1.053202
g         NaN
h   -2.359958
Name: one

In [722]: isnull(df2['one'])
Out[722]: 
a    False
b     True
c    False
d     True
e    False
f    False
g     True
h    False
Name: one

In [723]: df2['four'].notnull()
Out[723]: 
a     True
b    False
c     True
d    False
e     True
f     True
g    False
h     True

Summary: NaN, inf, -inf, and None (in object arrays) are all considered missing by the isnull and notnull functions.

Calculations with missing data

Missing values propagate naturally through arithmetic operations between pandas objects.

In [724]: a
Out[724]: 
        one       two
a  0.059117  1.138469
b  0.059117  1.138469
c -0.280853  0.025653
d -0.280853  0.025653
e  0.863937  0.252462

In [725]: b
Out[725]: 
        one       two     three
a  0.059117  1.138469 -2.400634
b       NaN       NaN       NaN
c -0.280853  0.025653 -1.386071
d       NaN       NaN       NaN
e  0.863937  0.252462  1.500571

In [726]: a + b
Out[726]: 
        one  three       two
a  0.118234    NaN  2.276938
b       NaN    NaN       NaN
c -0.561707    NaN  0.051306
d       NaN    NaN       NaN
e  1.727874    NaN  0.504923

The descriptive statistics and computational methods discussed in the data structure overview (and listed here and here) are all written to account for missing data. For example:

  • When summing data, NA (missing) values will be treated as zero
  • If the data are all NA, the result will be NA
  • Methods like cumsum and cumprod ignore NA values, but preserve them in the resulting arrays
In [727]: df
Out[727]: 
        one       two     three
a  0.059117  1.138469 -2.400634
b       NaN       NaN       NaN
c -0.280853  0.025653 -1.386071
d       NaN       NaN       NaN
e  0.863937  0.252462  1.500571
f  1.053202 -2.338595 -0.374279
g       NaN       NaN       NaN
h -2.359958 -1.157886 -0.551865

In [728]: df['one'].sum()
Out[728]: -0.66455558290247652

In [729]: df.mean(1)
Out[729]: 
a   -0.401016
b         NaN
c   -0.547090
d         NaN
e    0.872323
f   -0.553224
g         NaN
h   -1.356570

In [730]: df.cumsum()
Out[730]: 
        one       two     three
a  0.059117  1.138469 -2.400634
b       NaN       NaN       NaN
c -0.221736  1.164122 -3.786705
d       NaN       NaN       NaN
e  0.642200  1.416584 -2.286134
f  1.695403 -0.922011 -2.660413
g       NaN       NaN       NaN
h -0.664556 -2.079897 -3.212278

NA values in GroupBy

NA groups in GroupBy are automatically excluded. This behavior is consistent with R, for example.

Cleaning / filling missing data

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

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 [731]: df2
Out[731]: 
        one       two     three four   five
a  0.059117  1.138469 -2.400634  bar   True
b       NaN       NaN       NaN  NaN    NaN
c -0.280853  0.025653 -1.386071  bar  False
d       NaN       NaN       NaN  NaN    NaN
e  0.863937  0.252462  1.500571  bar   True
f  1.053202 -2.338595 -0.374279  bar   True
g       NaN       NaN       NaN  NaN    NaN
h -2.359958 -1.157886 -0.551865  bar  False

In [732]: df2.fillna(0)
Out[732]: 
        one       two     three four   five
a  0.059117  1.138469 -2.400634  bar   True
b  0.000000  0.000000  0.000000    0      0
c -0.280853  0.025653 -1.386071  bar  False
d  0.000000  0.000000  0.000000    0      0
e  0.863937  0.252462  1.500571  bar   True
f  1.053202 -2.338595 -0.374279  bar   True
g  0.000000  0.000000  0.000000    0      0
h -2.359958 -1.157886 -0.551865  bar  False

In [733]: df2['four'].fillna('missing')
Out[733]: 
a        bar
b    missing
c        bar
d    missing
e        bar
f        bar
g    missing
h        bar
Name: four

Fill gaps forward or backward

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

In [734]: df
Out[734]: 
        one       two     three
a  0.059117  1.138469 -2.400634
b       NaN       NaN       NaN
c -0.280853  0.025653 -1.386071
d       NaN       NaN       NaN
e  0.863937  0.252462  1.500571
f  1.053202 -2.338595 -0.374279
g       NaN       NaN       NaN
h -2.359958 -1.157886 -0.551865

In [735]: df.fillna(method='pad')
Out[735]: 
        one       two     three
a  0.059117  1.138469 -2.400634
b  0.059117  1.138469 -2.400634
c -0.280853  0.025653 -1.386071
d -0.280853  0.025653 -1.386071
e  0.863937  0.252462  1.500571
f  1.053202 -2.338595 -0.374279
g  1.053202 -2.338595 -0.374279
h -2.359958 -1.157886 -0.551865

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.

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 [736]: df
Out[736]: 
        one       two     three
a  0.059117  1.138469 -2.400634
b       NaN  0.000000  0.000000
c -0.280853  0.025653 -1.386071
d       NaN  0.000000  0.000000
e  0.863937  0.252462  1.500571
f  1.053202 -2.338595 -0.374279
g       NaN  0.000000  0.000000
h -2.359958 -1.157886 -0.551865

In [737]: df.dropna(axis=0)
Out[737]: 
        one       two     three
a  0.059117  1.138469 -2.400634
c -0.280853  0.025653 -1.386071
e  0.863937  0.252462  1.500571
f  1.053202 -2.338595 -0.374279
h -2.359958 -1.157886 -0.551865

In [738]: df.dropna(axis=1)
Out[738]: 
        two     three
a  1.138469 -2.400634
b  0.000000  0.000000
c  0.025653 -1.386071
d  0.000000  0.000000
e  0.252462  1.500571
f -2.338595 -0.374279
g  0.000000  0.000000
h -1.157886 -0.551865

In [739]: df['one'].dropna()
Out[739]: 
a    0.059117
c   -0.280853
e    0.863937
f    1.053202
h   -2.359958
Name: one

dropna is presently only implemented for Series and DataFrame, but will be eventually added to Panel. Series.dropna is a simpler method as it only has one axis to consider. DataFrame.dropna has considerably more options, which can be examined in the API.

Interpolation

A basic linear interpolate method has been implemented on Series with intended use for time series data. There has not been a great deal of demand for interpolation methods outside of the filling methods described above.

In [740]: fig, axes = plt.subplots(ncols=2, figsize=(8, 4))

In [741]: ts.plot(ax=axes[0])
Out[741]: <matplotlib.axes.AxesSubplot at 0x10e300650>

In [742]: ts.interpolate().plot(ax=axes[1])
Out[742]: <matplotlib.axes.AxesSubplot at 0x10c4fa2d0>

In [743]: axes[0].set_title('Not interpolated')
Out[743]: <matplotlib.text.Text at 0x10e3f00d0>

In [744]: axes[1].set_title('Interpolated')
Out[744]: <matplotlib.text.Text at 0x11388a3d0>

In [745]: plt.close('all')
_images/series_interpolate.png

Missing data casting rules and indexing

While pandas supports storing arrays of integer and boolean type, these types are not capable of storing missing data. Until we can switch to using a native NA type in NumPy, we’ve established some “casting rules” when reindexing will cause missing data to be introduced into, say, a Series or DataFrame. Here they are:

data type Cast to
integer float
boolean object
float no cast
object no cast

For example:

In [746]: s = Series(randn(5), index=[0, 2, 4, 6, 7])

In [747]: s > 0
Out[747]: 
0    False
2     True
4     True
6     True
7     True

In [748]: (s > 0).dtype
Out[748]: dtype('bool')

In [749]: crit = (s > 0).reindex(range(8))

In [750]: crit
Out[750]: 
0    False
1      NaN
2     True
3      NaN
4     True
5      NaN
6     True
7     True

In [751]: crit.dtype
Out[751]: dtype('object')

Ordinarily NumPy will complain if you try to use an object array (even if it contains boolean values) instead of a boolean array to get or set values from an ndarray (e.g. selecting values based on some criteria). If a boolean vector contains NAs, an exception will be generated:

In [752]: reindexed = s.reindex(range(8)).fillna(0)

In [753]: reindexed[crit]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-753-2da204ed1ac7> in <module>()
----> 1 reindexed[crit]
/Users/changshe/code/pandas/pandas/core/series.py in __getitem__(self, key)
    314         # special handling of boolean data with NAs stored in object
    315         # arrays. Since we can't represent NA with dtype=bool
--> 316         if _is_bool_indexer(key):
    317             key = self._check_bool_indexer(key)
    318             key = np.asarray(key, dtype=bool)
/Users/changshe/code/pandas/pandas/core/common.py in _is_bool_indexer(key)
    316         if not lib.is_bool_array(key):
    317             if isnull(key).any():
--> 318                 raise ValueError('cannot index with vector containing '
    319                                  'NA / NaN values')
    320             return False
ValueError: cannot index with vector containing NA / NaN values

However, these can be filled in using fillna and it will work fine:

In [754]: reindexed[crit.fillna(False)]
Out[754]: 
2    1.314232
4    0.690579
6    0.995761
7    2.396780

In [755]: reindexed[crit.fillna(True)]
Out[755]: 
1    0.000000
2    1.314232
3    0.000000
4    0.690579
5    0.000000
6    0.995761
7    2.396780