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 [1359]: df = DataFrame(randn(5, 3), index=['a', 'c', 'e', 'f', 'h'],
......: columns=['one', 'two', 'three'])
......:
In [1360]: df['four'] = 'bar'
In [1361]: df['five'] = df['one'] > 0
In [1362]: df
Out[1362]:
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 [1363]: df2 = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
In [1364]: df2
Out[1364]:
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”.
Until recently, for legacy reasons inf and -inf were also considered to be “null” in computations. This is no longer the case by default; use the mode.use_inf_as_null option to recover it.
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 [1365]: df2['one']
Out[1365]:
a 0.059117
b NaN
c -0.280853
d NaN
e 0.863937
f 1.053202
g NaN
h -2.359958
Name: one, dtype: float64
In [1366]: isnull(df2['one'])
Out[1366]:
a False
b True
c False
d True
e False
f False
g True
h False
Name: one, dtype: bool
In [1367]: df2['four'].notnull()
Out[1367]:
a True
b False
c True
d False
e True
f True
g False
h True
dtype: bool
Summary: NaN and None (in object arrays) are considered missing by the isnull and notnull functions. inf and -inf are no longer considered missing by default.
Datetimes¶
For datetime64[ns] types, NaT represents missing values. This is a pseudo-native sentinal value that can be represented by numpy in a singular dtype (datetime64[ns]). Pandas objects provide intercompatibility between NaT and NaN.
In [1368]: df2 = df.copy()
In [1369]: df2['timestamp'] = Timestamp('20120101')
In [1370]: df2
Out[1370]:
one two three four five timestamp
a 0.059117 1.138469 -2.400634 bar True 2012-01-01 00:00:00
c -0.280853 0.025653 -1.386071 bar False 2012-01-01 00:00:00
e 0.863937 0.252462 1.500571 bar True 2012-01-01 00:00:00
f 1.053202 -2.338595 -0.374279 bar True 2012-01-01 00:00:00
h -2.359958 -1.157886 -0.551865 bar False 2012-01-01 00:00:00
In [1371]: df2.ix[['a','c','h'],['one','timestamp']] = np.nan
In [1372]: df2
Out[1372]:
one two three four five timestamp
a NaN 1.138469 -2.400634 bar True NaT
c NaN 0.025653 -1.386071 bar False NaT
e 0.863937 0.252462 1.500571 bar True 2012-01-01 00:00:00
f 1.053202 -2.338595 -0.374279 bar True 2012-01-01 00:00:00
h NaN -1.157886 -0.551865 bar False NaT
In [1373]: df2.get_dtype_counts()
Out[1373]:
bool 1
datetime64[ns] 1
float64 3
object 1
dtype: int64
Calculations with missing data¶
Missing values propagate naturally through arithmetic operations between pandas objects.
In [1374]: a
Out[1374]:
one two
a NaN 1.138469
c NaN 0.025653
e 0.863937 0.252462
f 1.053202 -2.338595
h 1.053202 -1.157886
In [1375]: b
Out[1375]:
one two three
a NaN 1.138469 -2.400634
c NaN 0.025653 -1.386071
e 0.863937 0.252462 1.500571
f 1.053202 -2.338595 -0.374279
h NaN -1.157886 -0.551865
In [1376]: a + b
Out[1376]:
one three two
a NaN NaN 2.276938
c NaN NaN 0.051306
e 1.727874 NaN 0.504923
f 2.106405 NaN -4.677190
h NaN NaN -2.315772
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 [1377]: df
Out[1377]:
one two three
a NaN 1.138469 -2.400634
c NaN 0.025653 -1.386071
e 0.863937 0.252462 1.500571
f 1.053202 -2.338595 -0.374279
h NaN -1.157886 -0.551865
In [1378]: df['one'].sum()
Out[1378]: 1.917139050150438
In [1379]: df.mean(1)
Out[1379]:
a -0.631082
c -0.680209
e 0.872323
f -0.553224
h -0.854876
dtype: float64
In [1380]: df.cumsum()
Out[1380]:
one two three
a NaN 1.138469 -2.400634
c NaN 1.164122 -3.786705
e 0.863937 1.416584 -2.286134
f 1.917139 -0.922011 -2.660413
h NaN -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 [1381]: df2
Out[1381]:
one two three four five timestamp
a NaN 1.138469 -2.400634 bar True NaT
c NaN 0.025653 -1.386071 bar False NaT
e 0.863937 0.252462 1.500571 bar True 2012-01-01 00:00:00
f 1.053202 -2.338595 -0.374279 bar True 2012-01-01 00:00:00
h NaN -1.157886 -0.551865 bar False NaT
In [1382]: df2.fillna(0)
Out[1382]:
one two three four five timestamp
a 0.000000 1.138469 -2.400634 bar True 1970-01-01 00:00:00
c 0.000000 0.025653 -1.386071 bar False 1970-01-01 00:00:00
e 0.863937 0.252462 1.500571 bar True 2012-01-01 00:00:00
f 1.053202 -2.338595 -0.374279 bar True 2012-01-01 00:00:00
h 0.000000 -1.157886 -0.551865 bar False 1970-01-01 00:00:00
In [1383]: df2['four'].fillna('missing')
Out[1383]:
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 [1384]: df
Out[1384]:
one two three
a NaN 1.138469 -2.400634
c NaN 0.025653 -1.386071
e 0.863937 0.252462 1.500571
f 1.053202 -2.338595 -0.374279
h NaN -1.157886 -0.551865
In [1385]: df.fillna(method='pad')
Out[1385]:
one two three
a NaN 1.138469 -2.400634
c NaN 0.025653 -1.386071
e 0.863937 0.252462 1.500571
f 1.053202 -2.338595 -0.374279
h 1.053202 -1.157886 -0.551865
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 [1386]: df
Out[1386]:
one two three
a NaN 1.138469 -2.400634
c NaN 0.025653 -1.386071
e NaN NaN NaN
f NaN NaN NaN
h NaN -1.157886 -0.551865
In [1387]: df.fillna(method='pad', limit=1)
Out[1387]:
one two three
a NaN 1.138469 -2.400634
c NaN 0.025653 -1.386071
e NaN 0.025653 -1.386071
f NaN NaN NaN
h NaN -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 [1388]: df
Out[1388]:
one two three
a NaN 1.138469 -2.400634
c NaN 0.025653 -1.386071
e NaN 0.000000 0.000000
f NaN 0.000000 0.000000
h NaN -1.157886 -0.551865
In [1389]: df.dropna(axis=0)
Out[1389]:
Empty DataFrame
Columns: [one, two, three]
Index: []
In [1390]: df.dropna(axis=1)
Out[1390]:
two three
a 1.138469 -2.400634
c 0.025653 -1.386071
e 0.000000 0.000000
f 0.000000 0.000000
h -1.157886 -0.551865
In [1391]: df['one'].dropna()
Out[1391]: Series([], dtype: float64)
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 linear interpolate method has been implemented on Series. The default interpolation assumes equally spaced points.
In [1392]: ts.count()
Out[1392]: 61
In [1393]: ts.head()
Out[1393]:
2000-01-31 0.469112
2000-02-29 NaN
2000-03-31 NaN
2000-04-28 NaN
2000-05-31 NaN
Freq: BM, dtype: float64
In [1394]: ts.interpolate().count()
Out[1394]: 100
In [1395]: ts.interpolate().head()
Out[1395]:
2000-01-31 0.469112
2000-02-29 0.435428
2000-03-31 0.401743
2000-04-28 0.368059
2000-05-31 0.334374
Freq: BM, dtype: float64
In [1396]: ts.interpolate().plot()
Out[1396]: <matplotlib.axes.AxesSubplot at 0xf483950>
Index aware interpolation is available via the method keyword:
In [1397]: ts
Out[1397]:
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 [1398]: ts.interpolate()
Out[1398]:
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 [1399]: ts.interpolate(method='time')
Out[1399]:
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 [1400]: ser
Out[1400]:
0 0
1 NaN
10 10
dtype: float64
In [1401]: ser.interpolate()
Out[1401]:
0 0
1 5
10 10
dtype: float64
In [1402]: ser.interpolate(method='values')
Out[1402]:
0 0
1 1
10 10
dtype: float64
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 [1403]: ser = Series([0., 1., 2., 3., 4.])
In [1404]: ser.replace(0, 5)
Out[1404]:
0 5
1 1
2 2
3 3
4 4
dtype: float64
You can replace a list of values by a list of other values:
In [1405]: ser.replace([0, 1, 2, 3, 4], [4, 3, 2, 1, 0])
Out[1405]:
0 4
1 3
2 2
3 1
4 0
dtype: float64
You can also specify a mapping dict:
In [1406]: ser.replace({0: 10, 1: 100})
Out[1406]:
0 10
1 100
2 2
3 3
4 4
dtype: float64
For a DataFrame, you can specify individual values by column:
In [1407]: df = DataFrame({'a': [0, 1, 2, 3, 4], 'b': [5, 6, 7, 8, 9]})
In [1408]: df.replace({'a': 0, 'b': 5}, 100)
Out[1408]:
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 [1409]: ser.replace([1, 2, 3], method='pad')
Out[1409]:
0 0
1 0
2 0
3 0
4 4
dtype: float64
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 [1410]: s = Series(randn(5), index=[0, 2, 4, 6, 7])
In [1411]: s > 0
Out[1411]:
0 False
2 True
4 True
6 True
7 True
dtype: bool
In [1412]: (s > 0).dtype
Out[1412]: dtype('bool')
In [1413]: crit = (s > 0).reindex(range(8))
In [1414]: crit
Out[1414]:
0 False
1 NaN
2 True
3 NaN
4 True
5 NaN
6 True
7 True
dtype: object
In [1415]: crit.dtype
Out[1415]: dtype('O')
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 [1416]: reindexed = s.reindex(range(8)).fillna(0)
In [1417]: reindexed[crit]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-1417-2da204ed1ac7> in <module>()
----> 1 reindexed[crit]
/home/docbuild/CI/p2/pandas/core/series.pyc in __getitem__(self, key)
631 # special handling of boolean data with NAs stored in object
632 # arrays. Since we can't represent NA with dtype=bool
--> 633 if _is_bool_indexer(key):
634 key = _check_bool_indexer(self.index, key)
635
/home/docbuild/CI/p2/pandas/core/common.pyc in _is_bool_indexer(key)
1137 if not lib.is_bool_array(key):
1138 if isnull(key).any():
-> 1139 raise ValueError('cannot index with vector containing '
1140 'NA / NaN values')
1141 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 [1418]: reindexed[crit.fillna(False)]
Out[1418]:
2 1.314232
4 0.690579
6 0.995761
7 2.396780
dtype: float64
In [1419]: reindexed[crit.fillna(True)]
Out[1419]:
1 0.000000
2 1.314232
3 0.000000
4 0.690579
5 0.000000
6 0.995761
7 2.396780
dtype: float64