In this section, we will discuss missing (also referred to as NA) values in pandas.
::: tip 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.
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 “not available” or “NA”.
::: tip Note
If you want to consider inf and -inf to be “NA” in computations, you can set pandas.options.mode.use_inf_as_na = True.
In [4]: df Out[4]: one two three four five a 0.469112 -0.282863 -1.509059 bar True c -1.1356321.212112 -0.173215 bar False e 0.119209 -1.044236 -0.861849 bar True f -2.104569 -0.4949291.071804 bar False h 0.721555 -0.706771 -1.039575 bar True
In [6]: df2 Out[6]: one two three four five a 0.469112 -0.282863 -1.509059 bar True b NaN NaN NaN NaN NaN c -1.1356321.212112 -0.173215 bar False d NaN NaN NaN NaN NaN e 0.119209 -1.044236 -0.861849 bar True f -2.104569 -0.4949291.071804 bar False g NaN NaN NaN NaN NaN h 0.721555 -0.706771 -1.039575 bar True
To make detecting missing values easier (and across different array dtypes), pandas provides the isna() and notna() functions, which are also methods on Series and DataFrame objects:
In [7]: df2['one'] Out[7]: a 0.469112 b NaN c -1.135632 d NaN e 0.119209 f -2.104569 g NaN h 0.721555 Name: one, dtype: float64
In [8]: pd.isna(df2['one']) Out[8]: a False b True c False d True e False f False g True h False Name: one, dtype: bool
In [9]: df2['four'].notna() Out[9]: a True b False c True d False e True f True g False h True Name: four, dtype: bool
In [10]: df2.isna() Out[10]: one two three four five a FalseFalseFalseFalseFalse b TrueTrueTrueTrueTrue c FalseFalseFalseFalseFalse d TrueTrueTrueTrueTrue e FalseFalseFalseFalseFalse f FalseFalseFalseFalseFalse g TrueTrueTrueTrueTrue h FalseFalseFalseFalseFalse
::: danger Warning
One has to be mindful that in Python (and NumPy), the nan's don’t compare equal, but None'sdo. Note that pandas/NumPy uses the fact that np.nan != np.nan, and treats None like np.nan.
1 2 3 4 5
In [11]: None == None# noqa: E711 Out[11]: True
In [12]: np.nan == np.nan Out[12]: False
So as compared to above, a scalar equality comparison versus a None/np.nan doesn’t provide useful information.
1 2 3 4 5 6 7 8 9 10 11
In [13]: df2['one'] == np.nan Out[13]: a False b False c False d False e False f False g False h False Name: one, dtype: bool
:::
Integer dtypes and missing data
Because NaN is a float, a column of integers with even one missing values is cast to floating-point dtype (see Support for integer NA for more). Pandas provides a nullable integer array, which can be used by explicitly requesting the dtype:
1 2 3 4 5 6 7
In [14]: pd.Series([1, 2, np.nan, 4], dtype=pd.Int64Dtype()) Out[14]: 01 12 2 NaN 34 dtype: Int64
Alternatively, the string alias dtype='Int64' (note the capital "I") can be used.
For datetime64[ns] types, NaT represents missing values. This is a pseudo-native sentinel value that can be represented by NumPy in a singular dtype (datetime64[ns]). pandas objects provide compatibility between NaT and NaN.
In [16]: df2['timestamp'] = pd.Timestamp('20120101')
In [17]: df2 Out[17]: one two three four five timestamp a 0.469112 -0.282863 -1.509059 bar True2012-01-01 c -1.1356321.212112 -0.173215 bar False2012-01-01 e 0.119209 -1.044236 -0.861849 bar True2012-01-01 f -2.104569 -0.4949291.071804 bar False2012-01-01 h 0.721555 -0.706771 -1.039575 bar True2012-01-01
In [18]: df2.loc[['a', 'c', 'h'], ['one', 'timestamp']] = np.nan
In [19]: df2 Out[19]: one two three four five timestamp a NaN -0.282863 -1.509059 bar True NaT c NaN 1.212112 -0.173215 bar False NaT e 0.119209 -1.044236 -0.861849 bar True2012-01-01 f -2.104569 -0.4949291.071804 bar False2012-01-01 h NaN -0.706771 -1.039575 bar True NaT
In [28]: a Out[28]: one two a NaN -0.282863 c NaN 1.212112 e 0.119209 -1.044236 f -2.104569 -0.494929 h -2.104569 -0.706771
In [29]: b Out[29]: one two three a NaN -0.282863 -1.509059 c NaN 1.212112 -0.173215 e 0.119209 -1.044236 -0.861849 f -2.104569 -0.4949291.071804 h NaN -0.706771 -1.039575
In [30]: a + b Out[30]: one three two a NaN NaN -0.565727 c NaN NaN 2.424224 e 0.238417 NaN -2.088472 f -4.209138 NaN -0.989859 h NaN NaN -1.413542
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 0.
Cumulative methods like cumsum() and cumprod() ignore NA values by default, but preserve them in the resulting arrays. To override this behaviour and include NA values, use skipna=False.
In [31]: df Out[31]: one two three a NaN -0.282863 -1.509059 c NaN 1.212112 -0.173215 e 0.119209 -1.044236 -0.861849 f -2.104569 -0.4949291.071804 h NaN -0.706771 -1.039575
In [32]: df['one'].sum() Out[32]: -1.9853605075978744
In [33]: df.mean(1) Out[33]: a -0.895961 c 0.519449 e -0.595625 f -0.509232 h -0.873173 dtype: float64
In [34]: df.cumsum() Out[34]: one two three a NaN -0.282863 -1.509059 c NaN 0.929249 -1.682273 e 0.119209 -0.114987 -2.544122 f -1.985361 -0.609917 -1.472318 h NaN -1.316688 -2.511893
In [35]: df.cumsum(skipna=False) Out[35]: one two three a NaN -0.282863 -1.509059 c NaN 0.929249 -1.682273 e NaN -0.114987 -2.544122 f NaN -0.609917 -1.472318 h NaN -1.316688 -2.511893
Sum/prod of empties/nans
::: danger Warning
This behavior is now standard as of v0.22.0 and is consistent with the default in numpy; previously sum/prod of all-NA or empty Series/DataFrames would return NaN. See v0.22.0 whatsnew for more.
:::
The sum of an empty or all-NA Series or column of a DataFrame is 0.
1 2 3 4 5
In [36]: pd.Series([np.nan]).sum() Out[36]: 0.0
In [37]: pd.Series([]).sum() Out[37]: 0.0
The product of an empty or all-NA Series or column of a DataFrame is 1.
1 2 3 4 5
In [38]: pd.Series([np.nan]).prod() Out[38]: 1.0
In [39]: pd.Series([]).prod() Out[39]: 1.0
NA values in GroupBy
NA groups in GroupBy are automatically excluded. This behavior is consistent with R, for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
In [40]: df Out[40]: one two three a NaN -0.282863 -1.509059 c NaN 1.212112 -0.173215 e 0.119209 -1.044236 -0.861849 f -2.104569 -0.4949291.071804 h NaN -0.706771 -1.039575
In [41]: df.groupby('one').mean() Out[41]: two three one -2.104569 -0.4949291.071804 0.119209 -1.044236 -0.861849
See the groupby section here for more information.
Cleaning / filling missing data
pandas objects are equipped with various data manipulation methods for dealing with missing data.
Filling missing values: fillna
fillna() can “fill in” NA values with non-NA data in a couple of ways, which we illustrate:
In [42]: df2 Out[42]: one two three four five timestamp a NaN -0.282863 -1.509059 bar True NaT c NaN 1.212112 -0.173215 bar False NaT e 0.119209 -1.044236 -0.861849 bar True2012-01-01 f -2.104569 -0.4949291.071804 bar False2012-01-01 h NaN -0.706771 -1.039575 bar True NaT
In [43]: df2.fillna(0) Out[43]: one two three four five timestamp a 0.000000 -0.282863 -1.509059 bar True0 c 0.0000001.212112 -0.173215 bar False0 e 0.119209 -1.044236 -0.861849 bar True2012-01-01 00:00:00 f -2.104569 -0.4949291.071804 bar False2012-01-01 00:00:00 h 0.000000 -0.706771 -1.039575 bar True0
In [44]: df2['one'].fillna('missing') Out[44]: a missing c missing e 0.119209 f -2.10457 h missing Name: one, dtype: object
Fill gaps forward or backward
Using the same filling arguments as reindexing, we can propagate non-NA values forward or backward:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
In [45]: df Out[45]: one two three a NaN -0.282863 -1.509059 c NaN 1.212112 -0.173215 e 0.119209 -1.044236 -0.861849 f -2.104569 -0.4949291.071804 h NaN -0.706771 -1.039575
In [46]: df.fillna(method='pad') Out[46]: one two three a NaN -0.282863 -1.509059 c NaN 1.212112 -0.173215 e 0.119209 -1.044236 -0.861849 f -2.104569 -0.4949291.071804 h -2.104569 -0.706771 -1.039575
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
In [47]: df Out[47]: one two three a NaN -0.282863 -1.509059 c NaN 1.212112 -0.173215 e NaN NaN NaN f NaN NaN NaN h NaN -0.706771 -1.039575
In [48]: df.fillna(method='pad', limit=1) Out[48]: one two three a NaN -0.282863 -1.509059 c NaN 1.212112 -0.173215 e NaN 1.212112 -0.173215 f NaN NaN NaN h NaN -0.706771 -1.039575
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.
ffill() is equivalent to fillna(method='ffill') and bfill() is equivalent to fillna(method='bfill')
Filling with a PandasObject
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 [49]: dff = pd.DataFrame(np.random.randn(10, 3), columns=list('ABC'))
In [50]: dff.iloc[3:5, 0] = np.nan
In [51]: dff.iloc[4:6, 1] = np.nan
In [52]: dff.iloc[5:8, 2] = np.nan
In [53]: dff Out[53]: A B C 00.271860 -0.4249720.567020 10.276232 -1.087401 -0.673690 20.113648 -1.4784270.524988 3 NaN 0.577046 -1.715002 4 NaN NaN -1.157892 5 -1.344312 NaN NaN 6 -0.1090501.643563 NaN 70.357021 -0.674600 NaN 8 -0.968914 -1.2945240.413738 90.276662 -0.472035 -0.013960
In [54]: dff.fillna(dff.mean()) Out[54]: A B C 00.271860 -0.4249720.567020 10.276232 -1.087401 -0.673690 20.113648 -1.4784270.524988 3 -0.1408570.577046 -1.715002 4 -0.140857 -0.401419 -1.157892 5 -1.344312 -0.401419 -0.293543 6 -0.1090501.643563 -0.293543 70.357021 -0.674600 -0.293543 8 -0.968914 -1.2945240.413738 90.276662 -0.472035 -0.013960
In [55]: dff.fillna(dff.mean()['B':'C']) Out[55]: A B C 00.271860 -0.4249720.567020 10.276232 -1.087401 -0.673690 20.113648 -1.4784270.524988 3 NaN 0.577046 -1.715002 4 NaN -0.401419 -1.157892 5 -1.344312 -0.401419 -0.293543 6 -0.1090501.643563 -0.293543 70.357021 -0.674600 -0.293543 8 -0.968914 -1.2945240.413738 90.276662 -0.472035 -0.013960
Same result as above, but is aligning the ‘fill’ value which is a Series in this case.
1 2 3 4 5 6 7 8 9 10 11 12 13
In [56]: dff.where(pd.notna(dff), dff.mean(), axis='columns') Out[56]: A B C 00.271860 -0.4249720.567020 10.276232 -1.087401 -0.673690 20.113648 -1.4784270.524988 3 -0.1408570.577046 -1.715002 4 -0.140857 -0.401419 -1.157892 5 -1.344312 -0.401419 -0.293543 6 -0.1090501.643563 -0.293543 70.357021 -0.674600 -0.293543 8 -0.968914 -1.2945240.413738 90.276662 -0.472035 -0.013960
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 dropna():
In [57]: df Out[57]: one two three a NaN -0.282863 -1.509059 c NaN 1.212112 -0.173215 e NaN 0.0000000.000000 f NaN 0.0000000.000000 h NaN -0.706771 -1.039575
In [74]: df Out[74]: A B 01.00.25 12.1 NaN 2 NaN NaN 34.74.00 45.612.20 56.814.40
In [75]: df.interpolate() Out[75]: A B 01.00.25 12.11.50 23.42.75 34.74.00 45.612.20 56.814.40
The method argument gives access to fancier interpolation methods. If you have scipy installed, you can 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, consider method='akima'.
In [76]: df.interpolate(method='barycentric') Out[76]: A B 01.000.250 12.10 -7.660 23.53 -4.515 34.704.000 45.6012.200 56.8014.400
In [77]: df.interpolate(method='pchip') Out[77]: A B 01.000000.250000 12.100000.672808 23.434541.928950 34.700004.000000 45.6000012.200000 56.8000014.400000
In [78]: df.interpolate(method='akima') Out[78]: A B 01.0000000.250000 12.100000 -0.873316 23.4066670.320034 34.7000004.000000 45.60000012.200000 56.80000014.400000
When interpolating via a polynomial or spline approximation, you must also specify the degree or order of the approximation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
In [79]: df.interpolate(method='spline', order=2) Out[79]: A B 01.0000000.250000 12.100000 -0.428598 23.4045451.206900 34.7000004.000000 45.60000012.200000 56.80000014.400000
In [80]: df.interpolate(method='polynomial', order=2) Out[80]: A B 01.0000000.250000 12.100000 -2.703846 23.451351 -1.453846 34.7000004.000000 45.60000012.200000 56.80000014.400000
Compare several methods:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
In [81]: np.random.seed(2)
In [82]: ser = pd.Series(np.arange(1, 10.1, .25) ** 2 + np.random.randn(37))
In [85]: methods = ['linear', 'quadratic', 'cubic']
In [86]: df = pd.DataFrame({m: ser.interpolate(method=m) for m in methods})
In [87]: df.plot() Out[87]: <matplotlib.axes._subplots.AxesSubplot at 0x7f65d8a196a0>
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
In [88]: ser = pd.Series(np.sort(np.random.uniform(size=100)))
# interpolate at new_index In [89]: new_index = ser.index | pd.Index([49.25, 49.5, 49.75, 50.25, 50.5, 50.75])
In [90]: interp_s = ser.reindex(new_index).interpolate(method='pchip')
Like other pandas fill methods, interpolate() accepts a limit keyword argument. Use this argument to limit the number of consecutive NaN values filled since the last valid observation:
In [92]: ser = pd.Series([np.nan, np.nan, 5, np.nan, np.nan, ....: np.nan, 13, np.nan, np.nan]) ....:
In [93]: ser Out[93]: 0 NaN 1 NaN 25.0 3 NaN 4 NaN 5 NaN 613.0 7 NaN 8 NaN dtype: float64
# fill all consecutive values in a forward direction In [94]: ser.interpolate() Out[94]: 0 NaN 1 NaN 25.0 37.0 49.0 511.0 613.0 713.0 813.0 dtype: float64
# fill one consecutive value in a forward direction In [95]: ser.interpolate(limit=1) Out[95]: 0 NaN 1 NaN 25.0 37.0 4 NaN 5 NaN 613.0 713.0 8 NaN dtype: float64
By default, NaN values are filled in a forward direction. Use limit_direction parameter to fill backward or from both directions.
# fill one consecutive value backwards In [96]: ser.interpolate(limit=1, limit_direction='backward') Out[96]: 0 NaN 15.0 25.0 3 NaN 4 NaN 511.0 613.0 7 NaN 8 NaN dtype: float64
# fill one consecutive value in both directions In [97]: ser.interpolate(limit=1, limit_direction='both') Out[97]: 0 NaN 15.0 25.0 37.0 4 NaN 511.0 613.0 713.0 8 NaN dtype: float64
# fill all consecutive values in both directions In [98]: ser.interpolate(limit_direction='both') Out[98]: 05.0 15.0 25.0 37.0 49.0 511.0 613.0 713.0 813.0 dtype: float64
By default, NaN values are filled whether they are inside (surrounded by) existing valid values, or outside existing valid values. Introduced in v0.23 the limit_area parameter restricts filling to either inside or outside values.
# fill one consecutive inside value in both directions In [99]: ser.interpolate(limit_direction='both', limit_area='inside', limit=1) Out[99]: 0 NaN 1 NaN 25.0 37.0 4 NaN 511.0 613.0 7 NaN 8 NaN dtype: float64
# fill all consecutive outside values backward In [100]: ser.interpolate(limit_direction='backward', limit_area='outside') Out[100]: 05.0 15.0 25.0 3 NaN 4 NaN 5 NaN 613.0 7 NaN 8 NaN dtype: float64
# fill all consecutive outside values in both directions In [101]: ser.interpolate(limit_direction='both', limit_area='outside') Out[101]: 05.0 15.0 25.0 3 NaN 4 NaN 5 NaN 613.0 713.0 813.0 dtype: float64
Replacing generic values
Often times we want to replace arbitrary values with other values.
replace() in Series and replace() in DataFrame 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:
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):
1 2 3 4 5 6 7 8 9 10 11
In [109]: d = {'a': list(range(4)), 'b': list('ab..'), 'c': ['a', 'b', np.nan, 'd']}
In [110]: df = pd.DataFrame(d)
In [111]: df.replace('.', np.nan) Out[111]: a b c 00 a a 11 b b 22 NaN NaN 33 NaN d
Now do it with a regular expression that removes surrounding whitespace (regex -> regex):
1 2 3 4 5 6 7
In [112]: df.replace(r'\s*\.\s*', np.nan, regex=True) Out[112]: a b c 00 a a 11 b b 22 NaN NaN 33 NaN d
Replace a few different values (list -> list):
1 2 3 4 5 6 7
In [113]: df.replace(['a', '.'], ['b', np.nan]) Out[113]: a b c 00 b b 11 b b 22 NaN NaN 33 NaN d
list of regex -> list of regex:
1 2 3 4 5 6 7
In [114]: df.replace([r'\.', r'(a)'], ['dot', r'\1stuff'], regex=True) Out[114]: a b c 00 astuff astuff 11 b b 22 dot NaN 33 dot d
Only search in column 'b' (dict -> dict):
1 2 3 4 5 6 7
In [115]: df.replace({'b': '.'}, {'b': np.nan}) Out[115]: a b c 00 a a 11 b b 22 NaN NaN 33 NaN d
Same as the previous example, but use a regular expression for searching instead (dict of regex -> dict):
1 2 3 4 5 6 7
In [116]: df.replace({'b': r'\s*\.\s*'}, {'b': np.nan}, regex=True) Out[116]: a b c 00 a a 11 b b 22 NaN NaN 33 NaN d
You can pass nested dictionaries of regular expressions that use regex=True:
1 2 3 4 5 6 7
In [117]: df.replace({'b': {'b': r''}}, regex=True) Out[117]: a b c 00 a a 11 b 22 . NaN 33 . d
Alternatively, you can pass the nested dictionary like so:
1 2 3 4 5 6 7
In [118]: df.replace(regex={'b': {r'\s*\.\s*': np.nan}}) Out[118]: a b c 00 a a 11 b b 22 NaN NaN 33 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.
1 2 3 4 5 6 7
In [119]: df.replace({'b': r'\s*(\.)\s*'}, {'b': r'\1ty'}, regex=True) Out[119]: a b c 00 a a 11 b b 22 .ty NaN 33 .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).
1 2 3 4 5 6 7
In [120]: df.replace([r'\s*\.\s*', r'a|b'], np.nan, regex=True) Out[120]: a b c 00 NaN NaN 11 NaN NaN 22 NaN NaN 33 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:
1 2 3 4 5 6 7
In [121]: df.replace(regex=[r'\s*\.\s*', r'a|b'], value=np.nan) Out[121]: a b c 00 NaN NaN 11 NaN NaN 22 NaN NaN 33 NaN d
This can be convenient if you do not want to pass regex=True every time you want to use a regular expression.
::: tip Note
Anywhere in the above replace examples that you see a regular expression a compiled regular expression is valid as well.
In [122]: df = pd.DataFrame(np.random.randn(10, 2))
In [123]: df[np.random.rand(df.shape[0]) > 0.5] = 1.5
In [124]: df.replace(1.5, np.nan) Out[124]: 01 0 -0.844214 -1.021415 10.432396 -0.323580 20.4238250.799180 31.2626140.751965 4 NaN NaN 5 NaN NaN 6 -0.498174 -1.060799 70.591667 -0.183257 81.019855 -1.482465 9 NaN NaN
Replacing more than one value is possible by passing a list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
In [125]: df00 = df.iloc[0, 0]
In [126]: df.replace([1.5, df00], [np.nan, 'a']) Out[126]: 01 0 a -1.02141 10.432396 -0.32358 20.4238250.79918 31.262610.751965 4 NaN NaN 5 NaN NaN 6 -0.498174 -1.0608 70.591667 -0.183257 81.01985 -1.48247 9 NaN NaN
In [127]: df[1].dtype Out[127]: dtype('float64')
You can also operate on the DataFrame in place:
1
In [128]: df.replace(1.5, np.nan, inplace=True)
::: danger Warning
When replacing multiple bool or datetime64 objects, the first argument to replace (to_replace) must match the type of the value being replaced. For example,
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 GH6354 for more details.
:::
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 a reindexing operation introduces missing data, the Series will be cast according to the rules introduced in the table below.
In [131]: s = pd.Series(np.random.randn(5), index=[0, 2, 4, 6, 7])
In [132]: s > 0 Out[132]: 0True 2True 4True 6True 7True dtype: bool
In [133]: (s > 0).dtype Out[133]: dtype('bool')
In [134]: crit = (s > 0).reindex(list(range(8)))
In [135]: crit Out[135]: 0True 1 NaN 2True 3 NaN 4True 5 NaN 6True 7True dtype: object
In [136]: crit.dtype Out[136]: 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:
Pandas provides a nullable integer dtype, but you must explicitly request it when creating the series or column. Notice that we use a capital “I” in the dtype="Int64".
1 2 3 4 5 6 7 8 9 10
In [141]: s = pd.Series([0, 1, np.nan, 3, 4], dtype="Int64")
In [142]: s Out[142]: 00 11 2 NaN 33 44 dtype: Int64