pandas uses different sentinel values to represent a missing (also referred to as NA)
depending on the data type.
numpy.nan for NumPy data types. The disadvantage of using NumPy data types
is that the original data type will be coerced to np.float64 or object.
In [1]: pd.Series([1,2],dtype=
np
.
int64
)
.
reindex
([
0
,
1
,
2
])
Out[1]:
0 1.0
1 2.0
2 NaN
dtype: float64
In [2]:
pd
.
Series
([
True
,
False
],
dtype
=
np
.
bool_
)
.
reindex
([
0
,
1
,
2
])
Out[2]:
0 True
1 False
2 NaN
dtype: object
NaT for NumPy np.datetime64, np.timedelta64, and PeriodDtype. For typing applications,
use api.types.NaTType.
In [3]: pd.Series([1,2],dtype=np.dtype("timedelta64[ns]")).reindex([0,1,2])Out[3]: 0 0 days 00:00:00.0000000011 0 days 00:00:00.0000000022 NaTdtype: timedelta64[ns]In [4]: pd.Series([1,2],dtype=np.dtype("datetime64[ns]")).reindex([0,1,2])Out[4]: 0 1970-01-01 00:00:00.0000000011 1970-01-01 00:00:00.0000000022 NaTdtype: datetime64[ns]In [5]: pd.Series(["2020","2020"],dtype=pd.PeriodDtype("D")).reindex([0,1,2])Out[5]: 0 2020-01-011 2020-01-012 NaTdtype: period[D]
NA for StringDtype, Int64Dtype (and other bit widths),
Float64Dtype`(andotherbitwidths),:class:`BooleanDtype and ArrowDtype.
These types will maintain the original data type of the data.
For typing applications, use api.types.NAType.
Starting from pandas 1.0, an experimental NA value (singleton) is
available to represent scalar missing values. The goal of NA is provide a
“missing” indicator that can be used consistently across data types
(instead of np.nan, None or pd.NaT depending on the data type).
For example, when having missing values in a Series with the nullable integer
dtype, it will use NA:
Currently, pandas does not yet use those data types using NA by default
a DataFrame or Series, so you need to specify
the dtype explicitly. An easy way to convert to those dtypes is explained in the
conversion section.
Propagation in arithmetic and comparison operations
In general, missing values propagate in operations involving NA. When
one of the operands is unknown, the outcome of the operation is also unknown.
For example, NA propagates in arithmetic operations, similarly to
np.nan:
In [25]: pd.NA+1Out[25]: <NA>In [26]: "a"*pd.
Logical operations
For logical operations, NA follows the rules of the
three-valued logic (or
Kleene logic, similarly to R, SQL and Julia). This logic means to only
propagate missing values when it is logically required.
For example, for the logical “or” operation (|), if one of the operands
is True, we already know the result will be True, regardless of the
other value (so regardless the missing value would be True or False).
In this case, NA does not propagate:
NA in a boolean context
Since the actual value of an NA is unknown, it is ambiguous to convert NA
to a boolean value.
In [45]: bool(pd.NA)---------------------------------------------------------------------------TypeErrorTraceback (most recent call last)
CellIn[45],line1----> 1bool(pd.NA)File ~/work/pandas/pandas/pandas/_libs/missing.pyx:392, in pandas._libs.missing.NAType.__bool__
: boolean value of NA is ambiguous
NumPy ufuncs
pandas.NA implements NumPy’s __array_ufunc__ protocol. Most ufuncs
work with NA, and generally return NA:
In [46]: np.log(pd.NA)Out[46]: <NA>In [47]: np.add(pd
Inserting missing data
You can insert missing values by simply assigning to a Series or DataFrame.
The missing value sentinel used will be chosen based on the dtype.
The descriptive statistics and computational methods discussed in the
data structure overview (and listed here and here) are all
account for missing data.
When summing data, NA values or empty data will be treated as zero.
In [75]: pd.Series([np.nan]).sum()Out[75]: 0.0In [76]: pd.Series([],dtype="float64").sum()Out[76]: 0.0
When taking the product, NA values or empty data will be treated as 1.
In [77]: pd.Series([np.nan]).prod()Out[77]: 1.0In [78]: pd.Series([],dtype="float64").prod()Out[78]: 1.0
Cumulative methods like cumsum() and cumprod()
ignore NA values by default preserve them in the result. This behavior can be changed
with skipna
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 [95]: df.ffill(limit=1)Out[95]: np arrow0 1.0 1.01 1.0 1.02 NaN <NA>3 2.0 2.0
NA values can be replaced with corresponding value from a Series or DataFrame
where the index and column aligns between the original object and the filled object.
In [96]: dff=pd.DataFrame(np.arange(30,dtype=np.float64).reshape(10,3),columns=list("ABC"))In [97]: dff.iloc[
There are a few special cases when the result is known, even when one of the
operands is NA.
In [27]: pd.NA**0Out[27]: 1In [28]: 1**pd.NAOut[28]: 1
In equality and comparison operations, NA also propagates. This deviates
from the behaviour of np.nan, where comparisons with np.nan always
return False.
In [29]: pd.NA==1Out[29]: <NA>In [30]: pd.NA==pd.NAOut[30]: <NA>In [31]: pd.NA<2.5Out[31]: <NA>
In [33]: True|FalseOut[33]: TrueIn [34]: True|pd.NAOut[34]: TrueIn [35]: pd.NA|TrueOut[35]: True
On the other hand, if one of the operands is False, the result depends
on the value of the other operand. Therefore, in this case NA
propagates:
In [36]: False|TrueOut[36]: TrueIn [37]: False|FalseOut[37]: FalseIn [38]: False|pd.NAOut[38]: <NA>
The behaviour of the logical “and” operation (&) can be derived using
similar logic (where now NA will not propagate if one of the operands
is already False):
In [39]: False&TrueOut[39]: FalseIn [40]: False&FalseOut[40]: FalseIn [41]: False&pd.NAOut[41]: False
In [42]: True&TrueOut[42]: TrueIn [43]: True&FalseOut[43]: FalseIn [44]: True&pd.NAOut[44]: <NA>
()
TypeError
This also means that NA cannot be used in a context where it is
evaluated to a boolean, such as ifcondition:... where condition can
potentially be NA. In such cases, isna() can be used to check
for NA or condition being NA can be avoided, for example by
filling missing values beforehand.
If you have scipy installed, you can pass the name of a 1-d interpolation routine to method.
as specified in the scipy interpolation documentation and reference guide.
The appropriate interpolation method will depend on the data type.
When interpolating via a polynomial or spline approximation, you must also specify
the degree or order of the approximation:
By default, NaN values are filled whether they are surrounded by
existing valid values or outside existing valid values. The limit_area
parameter restricts filling to either inside or outside values.
# fill one consecutive inside value in both directionsIn [148]: ser.interpolate(limit_direction="both",limit_area="inside",limit=1)Out[148]: 0 NaN1 NaN2 5.03 7.04 NaN5 11.06 13.07 NaN8 NaNdtype: float64# fill all consecutive outside values backwardIn [149]: ser
DataFrame
(
np
.
eye
(
3
))
In [152]:
df
Out[152]:
0 1 2
0 1.0 0.0 0.0
1 0.0 1.0 0.0
2 0.0 0.0 1.0
In [153]:
df_missing
=
df
.
replace
(
0
,
np
.
nan
)
In [154]:
df_missing
Out[154]:
0 1 2
0 1.0 NaN NaN
1 NaN 1.0 NaN
2 NaN NaN 1.0
In [155]:
df_filled
=
df_missing
.
replace
(
np
.
nan
,
2
)
In [156]:
df_filled
Out[156]:
0 1 2
0 1.0 2.0 2.0
1 2.0 1.0 2.0
2 2.0 2.0 1.0
Replacing more than one value is possible by passing a list.
In [159]: d={"a":list(range(4)),"b":list("ab.."),"c":["a","b",np.nan,"d"]}In [160]: df=pd.DataFrame(d)In [161]: df.replace(".",np.nan)Out[161]: a b c0 0 a a1 1 b b2 2 NaN NaN3 3 NaN d
Replace the ‘.’ with NaN with regular expression that removes surrounding whitespace
In [162]: df.replace(r"\s*\.\s*",np.nan,regex=True)Out[162]: a b c0 0 a a1 1 b b2 2 NaN NaN3 3 NaN d
Replace with a list of regexes.
In [163]: df.replace([r"\.",r"(a)"],["dot",r"\1stuff"],regex=True)Out[163]: a b c0 0 astuff astuff1 1 b b2 2 dot NaN3 3 dot d
Replace with a regex in a mapping dict.
In [164]: df.replace({"b":r"\s*\.\s*"},{"b":np.nan},regex=True)Out[164]: a b c0 0 a a1 1 b b2 2 NaN NaN3 3 NaN d
Pass nested dictionaries of regular expressions that use the regex keyword.
In [165]: df.replace({"b":{"b":r""}},regex=True)Out[165]: a b c0 0 a a1 1 b2 2 . NaN3 3 . dIn [166]: df.replace(regex={"b":{r
Pass a list of regular expressions that will replace matches with a scalar.
In [168]: df.replace([r"\s*\.\s*",r"a|b"],"placeholder",regex=True)Out[168]: a b c0 0 placeholder placeholder1 1 placeholder placeholder2 2 placeholder NaN3 3 placeholder 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.
In [169]: df.replace(regex=[r"\s*\.\s*",r"a|b"],value="placeholder")Out[169]: a b c0 0 placeholder placeholder1 1 placeholder placeholder2 2 placeholder NaN3 3 placeholder d
df_conv
=
df
.
convert_dtypes
()
In [55]:
df_conv
Out[55]:
a b
0 <NA> True
1 2 <NA>
In [56]:
df_conv
.
dtypes
Out[56]:
a Int64
b boolean
dtype: object
=
"both"
)
Out[146]:
0 NaN
1 5.0
2 5.0
3 7.0
4 NaN
5 11.0
6 13.0
7 13.0
8 NaN
dtype: float64
In [147]:
ser
.
interpolate
(
limit_direction
=
"both"
)
Out[147]:
0 5.0
1 5.0
2 5.0
3 7.0
4 9.0
5 11.0
6 13.0
7 13.0
8 13.0
dtype: float64
.
interpolate
(
limit_direction
=
"backward"
,
limit_area
=
"outside"
)
Out[149]:
0 5.0
1 5.0
2 5.0
3 NaN
4 NaN
5 NaN
6 13.0
7 NaN
8 NaN
dtype: float64
# fill all consecutive outside values in both directions