The memory usage of a DataFrame (including the index) is shown when calling
the info(). A configuration option, display.memory_usage
(see the list of options), specifies if the
DataFrame memory usage will be displayed when invoking the
method.
info()
For example, the memory usage of the DataFrame below is shown
when calling info():
The + symbol indicates that the true memory usage could be higher, because
pandas does not count the memory used by values in columns with
dtype=object.
Passing memory_usage='deep' will enable a more accurate memory usage report,
accounting for the full usage of the contained objects. This is optional
as it can be expensive to do this deeper introspection.
By default the display option is set to True but can be explicitly
overridden by passing the memory_usage argument when invoking info().
The memory usage of each column can be found by calling the
memory_usage() method. This returns a Series with an index
represented by column names and memory usage of each column shown in bytes. For
the DataFrame above, the memory usage of each column and the total memory
usage can be found with the memory_usage() method:
In [8]: df.memory_usage()Out[8]: Index 128int64 40000float64 40000datetime64[ns] 40000timedelta64[ns] 40000complex128 80000object 40000bool 5000categorical 9968dtype: int64# total memory usage of dataframeIn [9]: df.memory_usage().sum()Out[9]: 295096
By default the memory usage of the DataFrame index is shown in the
returned Series, the memory usage of the index can be suppressed by passing
the index=False argument:
The memory usage displayed by the info() method utilizes the
memory_usage() method to determine the memory usage of a
DataFrame while also formatting the output in human-readable units (base-2
representation; i.e. 1KB = 1024 bytes).
pandas follows the NumPy convention of raising an error when you try to convert
something to a bool. This happens in an if-statement or when using the
boolean operations: and, or, and not. It is not clear what the result
of the following code should be:
>>> ifpd.Series([False,True,False]):... pass
Should it be True because it’s not zero-length, or False because there
are False values? It is unclear, so instead, pandas raises a ValueError:
In [11]: ifpd.Series([False,True,False]): ....: print("I was true") ....: ---------------------------------------------------------------------------ValueErrorTraceback (most recent call last)
<ipython-input-11-5c782b38cd2f> in ?()----> 1ifpd.Series([False,True,False
in
: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
You need to explicitly choose what you want to do with the DataFrame, e.g.
use any(), all() or empty().
Alternatively, you might want to compare if the pandas object is None:
In [12]: ifpd.Series([False,True,False])isnotNone: ....: print("I was not None") ....: I was not None
Below is how to check if any of the values are True:
In [13]: ifpd.Series([False,True,False]).any(): ....: print("I am any") ....: I am any
Bitwise boolean
Bitwise boolean operators like == and != return a boolean Series
which performs an element-wise comparison when compared to a scalar.
In [14]: s=pd.Series(range(5))In [15]: s==4Out[15]: 0 False1 False2 False
Using the in operator
Using the Python in operator on a Series tests for membership in the
index, not membership among the values.
In [16]: s=pd.Series(range(5),index=list("abcde"))In [17]: 2
It is a general rule in programming that one should not mutate a container
while it is being iterated over. Mutation will invalidate the iterator,
causing unexpected behavior. Consider the example:
One probably would have expected that the result would be [1,3,5].
When using a pandas method that takes a UDF, internally pandas is often
iterating over the
DataFrame or other pandas object. Therefore, if the UDF mutates (changes)
the DataFrame, unexpected behavior can arise.
In [25]: deff(s): ....: s.pop("a") ....: returns ....: In [26]: df=pd.DataFrame({"a":[1,2,3],"b":[4
Traceback (most recent call last)
in
in
in
in
in
: 'a'
Traceback (most recent call last)
in
in
in
in
in
in
in
in
in
in
: 'a'
To resolve this issue, one can make a copy so that the mutation does
not apply to the container being iterated over.
In [28]: values=[0,1,2,3,4,5]In [29]: n_removed=0In [30]: fork,valueinenumerate(values.copy()): ....: idx=k-
In [32]: deff(s): ....: s=s.copy() ....: s.pop("a") ....: returns ....: In [33]: df=pd.DataFrame({"a":[1,2
Missing value representation for NumPy types
np.nan as the NA representation for NumPy types
For lack of NA (missing) support from the ground up in NumPy and Python in
general, NA could have been represented with:
A masked array solution: an array of data and an array of boolean values
indicating whether a value is there or is missing.
Using a special sentinel value, bit pattern, or set of sentinel values to
denote NA across the dtypes.
The special value np.nan (Not-A-Number) was chosen as the NA value for NumPy types, and there are API
functions like DataFrame.isna() and DataFrame.notna() which can be used across the dtypes to
detect NA values. However, this choice has a downside of coercing missing integer data as float types as
shown in Support for integer NA.
NA type promotions for NumPy types
When introducing NAs into an existing Series or DataFrame via
reindex() or some other means, boolean and integer types will be
promoted to a different dtype in order to store the NAs. The promotions are
summarized in this table:
Typeclass
Support for integer NA
In the absence of high performance NA support being built into NumPy from
the ground up, the primary casualty is the ability to represent NAs in integer
arrays. For example:
In [35]: s=pd.Series([1,2,3,4,5],index=list("abcde"))In [36]:
Why not make NumPy like R?
Many people have suggested that NumPy should simply emulate the NA support
present in the more domain-specific statistical programming language R. Part of the reason is the
NumPy type hierarchy.
The R language, by contrast, only has a handful of built-in data types:
integer, numeric (floating-point), character, and
boolean. NA types are implemented by reserving special bit patterns for
each type to be used as the missing value. While doing this with the full NumPy
type hierarchy would be possible, it would be a more substantial trade-off
(especially for the 8- and 16-bit data types) and implementation undertaking.
However, R NA semantics are now available by using masked NumPy types such as
or PyArrow types ().
pandas is not 100% thread safe. The known issues relate to
the copy() method. If you are doing a lot of copying of
DataFrame objects shared among threads, we recommend holding locks inside
the threads where the data copying occurs.
Occasionally you may have to deal with data that were created on a machine with
a different byte order than the one on which you are running Python. A common
symptom of this issue is an error like:
To deal
with this issue you should convert the underlying NumPy array to the native
system byte order before passing it to Series or DataFrame
constructors using something similar to the following:
In [49]: x=np.array(list(range(10)),">i4")# big endianIn [50]: newx=x.byteswap().view(x.dtype.newbyteorder())# force native byteorderIn [51]: s=pd.
If this behavior is surprising, keep in mind that using in on a Python
dictionary tests keys, not values, and Series are dict-like.
To test for membership in the values, use the method isin():
In [19]: s.isin([2])Out[19]: a Falseb Falsec Trued Falsee Falsedtype: boolIn [20]: s.isin([2]).any()Out[20]: True
For DataFrame, likewise, in applies to the column axis,
testing for membership in the list of column names.