Here we discuss a lot of the essential functionality common to the pandas data
structures. To begin, let’s create some example objects like we did in
the 10 minutes to pandas section:
In [1]: index=pd.date_range("1/1/2000",periods=8)In [2]: s=pd.Series(np.random
.
randn
(
5
),
index
=
[
"a"
,
"b"
,
"c"
,
"d"
,
"e"
])
In [3]:
df
=
pd
.
DataFrame
(
np
.
random
.
randn
(
8
,
3
),
index
=
index
,
columns
=
[
"A"
,
"B"
,
"C"
])
Head and tail
To view a small sample of a Series or DataFrame object, use the
head() and tail() methods. The default number
of elements to display is five, but you may pass a custom number.
pandas objects have a number of attributes enabling you to access the metadata
shape: gives the axis dimensions of the object, consistent with ndarray
Axis labels
Series: index (only axis)
DataFrame: index (rows) and columns
Note, these attributes can be safely assigned to!
In [7]: df[:2]Out[7]: A B C2000-01-01 -0.173215 0.119209 -1.0442362000-01-02 -0.861849 -2.104569 -0.494929In [8]: df.columns=[x.lower()forxindf.columns]In [9]: dfOut[9]: a b c2000-01-01 -0.173215 0.119209 -1.0442362000-01-02 -0.861849 -2.104569 -0.4949292000-01-03 1.071804 0.721555 -0.7067712000-01-04 -1.039575 0.271860 -0.4249722000-01-05 0.567020 0.276232 -1.0874012000-01-06 -0.673690 0.113648 -1.4784272000-01-07 0.524988 0.404705 0.5770462000-01-08 -1.715002 -1.039268 -0.370647
pandas objects (Index, Series, DataFrame) can be
thought of as containers for arrays, which hold the actual data and do the
actual computation. For many types, the underlying array is a
numpy.ndarray. However, pandas and 3rd party libraries may extend
NumPy’s type system to add support for custom arrays
(see dtypes).
To get the actual data inside a Index or Series, use
the .array property
array will always be an ExtensionArray.
The exact details of what an ExtensionArray is and why pandas uses them are a bit
beyond the scope of this introduction. See dtypes for more.
If you know you need a NumPy array, use to_numpy()
or numpy.asarray().
When the Series or Index is backed by
an ExtensionArray, to_numpy()
may involve copying data and coercing values. See dtypes for more.
to_numpy() gives some control over the dtype of the
resulting numpy.ndarray. For example, consider datetimes with timezones.
NumPy doesn’t have a dtype to represent timezone-aware datetimes, so there
are two possibly useful representations:
In [16]: ser.to_numpy(dtype="datetime64[ns]")Out[16]: array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00.000000000'], dtype='datetime64[ns]')
Getting the “raw data” inside a DataFrame is possibly a bit more
complex. When your DataFrame only has a single data type for all the
columns, DataFrame.to_numpy() will return the underlying data:
If a DataFrame contains homogeneously-typed data, the ndarray can
actually be modified in-place, and the changes will be reflected in the data
structure. For heterogeneous data (e.g. some of the DataFrame’s columns are not
all the same dtype), this will not be the case. The values attribute itself,
unlike the axis labels, cannot be assigned to.
In the past, pandas recommended Series.values or DataFrame.values
for extracting the data from a Series or DataFrame. You’ll still find references
to these in old code bases and online. Going forward, we recommend avoiding
.values and using .array or .to_numpy(). .values has the following
drawbacks:
When your Series contains an extension type, it’s
unclear whether Series.values returns a NumPy array or the extension array.
Series.array will always return an ExtensionArray, and will never
copy data. Series.to_numpy() will always return a NumPy array,
potentially at the cost of copying / coercing values.
When your DataFrame contains a mixture of data types, may
involve copying data and coercing values to a common dtype, a relatively expensive
operation. , being a method, makes it clearer that the
returned NumPy array may not be a view on the same data in the DataFrame.
Accelerated operations
pandas has support for accelerating certain types of binary numerical and boolean operations using
the numexpr library and the bottleneck libraries.
These libraries are especially useful when dealing with large data sets, and provide large
speedups. numexpr uses smart chunking, caching, and multiple cores. bottleneck is
a set of specialized cython routines that are especially fast when dealing with arrays that have
nans.
Here is a sample (using 100 column x 100,000 row DataFrames):
Operation
0.11.0 (ms)
Prior Version (ms)
Ratio to Prior
df1>df2
13.32
125.35
0.1063
df1*df2
21.71
36.63
0.5928
You are highly encouraged to install both libraries. See the section
Recommended Dependencies for more installation info.
These are both enabled to be used by default, you can control this by setting the options:
With binary operations between pandas data structures, there are two key points
of interest:
Broadcasting behavior between higher- (e.g. DataFrame) and
lower-dimensional (e.g. Series) objects.
Missing data in computations.
We will demonstrate how to manage these issues independently, though they can
be handled simultaneously.
Matching / broadcasting behavior
DataFrame has the methods add(), sub(),
mul(), div() and related functions
radd(), rsub(), …
for carrying out binary operations. For broadcasting behavior,
Series input is of primary interest. Using these functions, you can use to
either match on the index or columns via the axis keyword:
In [18]: df=pd.DataFrame( ....: { ....: "one":pd.Series(np.random.randn(3),index=["a","b","c"]), ....: "two":
Furthermore you can align a level of a MultiIndexed DataFrame with a Series.
In [26]: dfmi=df.copy()In [27]: dfmi.index=pd.MultiIndex.from_tuples( ....: [(1,"a"),(1,"b"),(1,"c"),(2,
Series and Index also support the divmod() builtin. This function takes
the floor division and modulo operation at the same time returning a two-tuple
of the same type as the left hand side. For example:
In [39]: div,rem=divmod(s,[2,2,3,3,4,4,5,5,6,6])In [40]: divOut[40]: 0 01 02 0
Missing data / operations with fill values
In Series and DataFrame, the arithmetic functions have the option of inputting
a fill_value, namely a value to substitute when at most one of the values at
a location are missing. For example, when adding two DataFrame objects, you may
wish to treat NaN as 0 unless both DataFrames are missing that value, in which
case the result will be NaN (you can later replace NaN with some other value
using fillna if you wish).
In [42]: df2=df.copy()In [43]: df2.loc["a","three"]=1.0In [44]: dfOut[44]: one two three
Flexible comparisons
Series and DataFrame have the binary comparison methods eq, ne, lt, gt,
le, and ge whose behavior is analogous to the binary
arithmetic operations described above:
In [48]: df.gt(df2)Out[48]: one two threea False False Falseb False False False
Boolean reductions
You can apply the reductions: empty, any(),
all(), and bool() to provide a
way to summarize a boolean result.
In [50]: (df>0
Comparing if objects are equivalent
Often you may find that there is more than one way to compute the same
result. As a simple example, consider df+df and df*2. To test
that these two computations produce the same result, given the tools
shown above, you might imagine using (df+df==df*2).all(). But in
fact, this expression is False:
In [57]: df+df==df*2Out[57]: one two threea True True Falseb True True True
Comparing array-like objects
You can conveniently perform element-wise comparisons when comparing a pandas
data structure with a scalar value:
In [65]: pd.Series(["foo","bar","baz"])=="foo"Out[65]: 0 True1 False2 Falsedtype: boolIn [66]: pd.Index(["foo","bar","baz"])==
Combining overlapping data sets
A problem occasionally arising is the combination of two similar data sets
where values in one are preferred over the other. An example would be two data
series representing a particular economic indicator where one is considered to
be of “higher quality”. However, the lower quality series might extend further
back in history or have more complete data coverage. As such, we would like to
combine two DataFrame objects where missing values in one DataFrame are
conditionally filled with like-labeled values from the other DataFrame. The
function implementing this operation is combine_first(),
which we illustrate:
In [71]: df1=pd.DataFrame( ....: {"A":[1.0,np.nan,
General DataFrame combine
The combine_first() method above calls the more general
DataFrame.combine(). This method takes another DataFrame
and a combiner function, aligns the input DataFrame and then passes the combiner
function pairs of Series (i.e., columns whose names are the same).
There exists a large number of methods for computing descriptive statistics and
other related operations on Series, DataFrame. Most of these
are aggregations (hence producing a lower-dimensional result) like
sum(), mean(), and quantile(),
but some of them, like cumsum() and cumprod(),
produce an object of the same size. Generally speaking, these methods take an
axis argument, just like ndarray.{sum, std, …}, but the axis can be
specified by name or integer:
In [78]: dfOut[78]: one two threea 1.394981 1.772517 NaNb 0.343054 1.912123 -0.050390c 0.695246 1.478369 1.227435d NaN 0.279344 -0.613172In [79]: df.mean(0)Out[79]: one 0.811094two 1.360588three 0.187958dtype: float64In [80]: df.mean(1)Out[80]: a 1.583749b 0.734929c 1.133683d -0.166914dtype: float64
All such methods have a skipna option signaling whether to exclude missing
data (True by default):
In [81]: df.sum(0,skipna=False)Out[81]: one NaNtwo 5.442353three NaNdtype: float64In [82]: df.sum(axis=1,skipna=True)Out[82]: a 3.167498b 2.204786c 3.401050d -0.333828dtype: float64
Combined with the broadcasting / arithmetic behavior, one can describe various
statistical procedures, like standardization (rendering data zero mean and
standard deviation of 1), very concisely:
In [83]: ts_stand=(df-df.mean())/df.std()In [84]: ts_stand.std()Out[84]: one 1.0two 1.0three 1.0dtype: float64In [85]: xs_stand=df.sub(df.mean(1
Note that methods like cumsum() and cumprod()
preserve the location of NaN values. This is somewhat different from
expanding() and rolling() since NaN behavior
is furthermore dictated by a min_periods parameter.
In [87]: df.cumsum()Out[87]: one two threea 1.394981 1.772517 NaNb 1.738035 3.684640 -0.050390c 2.433281 5.163008 1.177045d NaN 5.442353 0.563873
Here is a quick reference summary table of common functions. Each also takes an
optional level parameter which applies only if the object has a
hierarchical index.
Function
Description
count
Number of non-NA observations
sum
Sum of values
Note that by chance some NumPy methods, like mean, std, and sum,
will exclude NAs on Series input by default:
In [88]: np.mean(df["one"])Out[88]: 0.8110935116651192In [89]: np.mean(df["one"].to_numpy())Out[89]: nan
Series.nunique() will return the number of unique non-NA values in a
Series:
In [90]: series=pd.Series(np.random.randn(500))In [91]: series[20:500]=np.nanIn [92]: series[10:20]=5In [93]: series.
Summarizing data: describe
There is a convenient describe() function which computes a variety of summary
statistics about a Series or the columns of a DataFrame (excluding NAs of
course):
In [94]: series=pd.Series(np.random.randn(1000))In [95]: series[::2]=np.
Index of min/max values
The idxmin() and idxmax() functions on Series
and DataFrame compute the index labels with the minimum and maximum
corresponding values:
In [108]: s1=pd.Series(np.random.randn(5))In [109]: s1
Value counts (histogramming) / mode
The value_counts() Series method computes a histogram
of a 1D array of values. It can also be used as a function on regular arrays:
Continuous values can be discretized using the cut() (bins based on values)
and qcut() (bins based on sample quantiles) functions:
In [129]: arr=np.random.randn(20)In [130]: factor=pd.cut(arr
Function application
To apply your own or another library’s functions to pandas objects,
you should be aware of the three methods below. The appropriate
method to use depends on whether your function expects to operate
on an entire DataFrame or Series, row- or column-wise, or elementwise.
DataFrames and Series can be passed into functions.
However, if the function needs to be called in a chain, consider using the pipe() method.
First some setup:
In [140]: defextract_city_name(df): .....: """ .....: Chicago, IL -> Chicago for city_name column .....: """ .....: df
Row or column-wise function application
Arbitrary functions can be applied along the axes of a DataFrame
using the apply() method, which, like the descriptive
statistics methods, takes an optional axis argument:
In [145]: df.apply(lambdax:np.mean(x))Out[145]: one 0.811094two 1.360588three 0.187958dtype: float64In [146]:
Aggregation API
The aggregation API allows one to express possibly multiple aggregation operations in a single concise way.
This API is similar across pandas objects, see groupby API, the
window API, and the resample API.
The entry point for aggregation is DataFrame.aggregate(), or the alias
DataFrame.agg().
We will use a similar starting frame from above:
In [161]: tsdf=pd
Transform API
The transform() method returns an object that is indexed the same (same size)
as the original. This API allows you to provide multiple operations at the same
time rather than one-by-one. Its API is quite similar to the .agg API.
We create a frame similar to the one used in the above sections.
In [182]: tsdf=pd.DataFrame( .....: np.random.randn(10,3
Applying elementwise functions
Since not all functions can be vectorized (accept NumPy arrays and return
another array or value), the methods map() on DataFrame
and analogously map() on Series accept any Python function taking
a single value and returning a single value. For example:
In [194]: df4=df.copy()In [195]: df4Out[195]: one two threea 1.394981 1.772517 NaNb 0.343054 1.912123 -0.050390c 0.695246 1.478369 1.227435
Reindexing and altering labels
reindex() is the fundamental data alignment method in pandas.
It is used to implement nearly all other features relying on label-alignment
functionality. To reindex means to conform the data to match a given set of
labels along a particular axis. This accomplishes several things:
Reorders the existing data to match a new set of labels
Inserts missing value (NA) markers in label locations where no data for
that label existed
If specified, fill data for missing labels using logic (highly relevant
to working with time series data)
Here is a simple example:
In [203]: s=pd.Series(np.random.randn(5),index=["a","b","c","d","e"])In [204]: sOut[204]: a 1.695148b 1.328614c 1.234686d -0.385845e -1.326508dtype: float64In [205]: s.reindex(["e","b","f","d"])Out[205]: e -1.326508b 1.328614f NaNd -0.385845dtype: float64
Here, the f label was not contained in the Series and hence appears as
NaN in the result.
With a DataFrame, you can simultaneously reindex the index and columns:
In [206]: dfOut[206]: one two threea 1.394981 1.772517 NaNb 0.343054 1.912123 -0.050390c 0.695246 1.478369 1.227435d NaN 0.279344 -0.613172In [207]: df.reindex(index=["c","f","b"],columns=["three","two","one"])Out[207]: three two onec 1.227435 1.478369 0.695246
Note that the Index objects containing the actual axis labels can be
shared between objects. So if we have a Series and a DataFrame, the
following can be done:
In [208]: rs=s.reindex(df.index)In [209]: rsOut[209]: a 1.695148b 1.328614c 1.234686d -0.385845dtype: float64In [210]: rs.indexisdf.indexOut[210]: True
This means that the reindexed Series’s index is the same Python object as the
DataFrame’s index.
DataFrame.reindex() also supports an “axis-style” calling convention,
where you specify a single labels argument and the axis it applies to.
In [211]: df.reindex(["c","f","b"],axis="index")Out[211]: one two threec 0.695246 1.478369 1.227435f NaN NaN NaNb 0.343054 1.912123 -0.050390In [212]: df.reindex(["three","two","one"],axis="columns")Out[212]:
Reindexing to align with another object
You may wish to take an object and reindex its axes to be labeled the same as
another object. While the syntax for this is straightforward albeit verbose, it
is a common enough operation that the reindex_like() method is
available to make this simpler:
In [213]: df2=df.reindex(["a","b","c"],columns=["one","two"])In [214]:
Aligning objects with each other with align
The align() method is the fastest way to simultaneously align two objects. It
supports a join argument (related to joining and merging):
join='outer': take the union of the indexes (default)
join='left': use the calling object’s index
join='right': use the passed object’s index
: intersect the indexes
Filling while reindexing
reindex() takes an optional parameter method which is a
filling method chosen from the following table:
Method
Action
pad / ffill
Fill values forward
bfill / backfill
Limits on filling while reindexing
The limit and tolerance arguments provide additional control over
filling while reindexing. Limit specifies the maximum count of consecutive
matches:
In [237]: ts2.reindex(ts.index,method="ffill",limit=1)Out[237]: 2000-01-03 0.1830512000-01-04 0.1830512000-01-05 NaN2000-01-06 2.395489
Dropping labels from an axis
A method closely related to reindex is the drop() function.
It removes a set of labels from an axis:
In [239]: dfOut[239]: one two threea 1.394981 1.772517 NaNb 0.343054 1.912123 -0.050390c 0.695246 1.478369 1.227435d NaN 0.279344 -0.613172In [240]: df.drop(["a","d"],axis=
Renaming / mapping labels
The rename() method allows you to relabel an axis based on some
mapping (a dict or Series) or an arbitrary function.
In [243]: sOut[243]: a -0.186646b -1.692424c -0.303893d -1.425662e 1.114285dtype: float64In [244]: s.rename(str.upper)Out[244]: A -0.186646B -1.692424C -0.303893
Iteration
The behavior of basic iteration over pandas objects depends on the type.
When iterating over a Series, it is regarded as array-like, and basic iteration
produces the values. DataFrames follow the dict-like convention of iterating
over the “keys” of the objects.
In short, basic iteration (foriinobject) produces:
Series: values
DataFrame: column labels
Thus, for example, iterating over a DataFrame gives you the column names:
In [253]: df=pd.DataFrame( .....: {"col1":np.random.randn(3),"col2":np.random.randn(3)},index=["a","b","c"] .....: ) .....: In [254]: forcolindf: .....: print(col) .....: col1col2
pandas objects also have the dict-like items() method to
iterate over the (key, value) pairs.
To iterate over the rows of a DataFrame, you can use the following methods:
iterrows(): Iterate over the rows of a DataFrame as (index, Series) pairs.
This converts the rows to Series objects, which can change the dtypes and has some
performance implications.
itertuples(): Iterate over the rows of a DataFrame
as namedtuples of the values. This is a lot faster than
iterrows(), and is in most cases preferable to use
to iterate over the values of a DataFrame.
items
Consistent with the dict-like interface, items() iterates
through key-value pairs:
Series: (index, scalar value) pairs
DataFrame: (column, Series) pairs
For example:
In [258]: forlabel,serindf.items(): .....: print(label) .....: print(
iterrows
iterrows() allows you to iterate through the rows of a
DataFrame as Series objects. It returns an iterator yielding each
index value along with a Series containing the data in each row:
In [259]: forrow_index,rowindf.iterrows(): .....: print(row_index,row,sep="\n")
itertuples
The itertuples() method will return an iterator
yielding a namedtuple for each row in the DataFrame. The first element
of the tuple will be the row’s corresponding index value, while the
remaining values are the row values.
This method does not convert the row to a Series object; it merely
returns the values inside a namedtuple. Therefore,
preserves the data type of the values
and is generally faster as .
.dt accessor
Series has an accessor to succinctly return datetime like properties for the
values of the Series, if it is a datetime/period like Series.
This will return a Series, indexed like the existing Series.
# timedeltaIn [292]: s=pd.Series(pd.timedelta_range("1 day 00:00:05",periods=4,freq="s"))In [293]: sOut[293]: 0 1 days 00:00:051 1 days 00:00:062 1 days 00:00:073 1 days 00:00:08dtype: timedelta64[ns]In [294]: s.dt.days
Vectorized string methods
Series is equipped with a set of string processing methods that make it easy to
operate on each element of the array. Perhaps most importantly, these methods
exclude missing/NA values automatically. These are accessed via the Series’s
str attribute and generally have names matching the equivalent (scalar)
built-in string methods. For example:
Powerful pattern-matching methods are provided as well, but note that
pattern-matching generally uses regular expressions by default (and in some cases
always uses them).
In [299]: df=pd.DataFrame( .....: { .....: "one":pd.Series(np.random.randn(3),index=["a","b","c"]), .....: "two":pd.Series(np.random.randn(4),index=["a","b","c","d"]), .....: "three":pd.Series(np.random.randn(3),index=["b","c","d"]), .....: } .....: ) .....: In [300]: unsorted_df=df.reindex( .....: index=["a","d","c","b"],columns=["three","two","one"] .....: ) .....: In [301]: unsorted_dfOut[301]: three two onea NaN -1.152244 0.562973d -0.252916 -0.109597 NaNc 1.273388 -0.167123 0.640382b -0.098217 0.009797 -1.299504# DataFrameIn [302]: unsorted_df.sort_index()Out[302]: three two onea NaN -1.152244 0.562973b -0.098217 0.009797 -1.299504c 1.273388 -0.167123 0.640382d -0.252916 -0.109597 NaNIn [303]: unsorted_df.sort_index(ascending=False)Out[303]: three two oned -0.252916 -0.109597 NaNc 1.273388 -0.167123 0.640382b -0.098217 0.009797 -1.299504a NaN -1.152244 0.562973In [304]: unsorted_df.sort_index(axis=1)Out[304]: one three twoa 0.562973 NaN -1.152244d NaN -0.252916 -0.109597c 0.640382 1.273388 -0.167123b -1.299504 -0.098217 0.009797# SeriesIn [305]: unsorted_df["three"].sort_index()Out[305]: a NaNb -0.098217c 1.273388d -0.252916Name: three, dtype: float64
Sorting by index also supports a key parameter that takes a callable
function to apply to the index being sorted. For MultiIndex objects,
the key is applied per-level to the levels specified by level.
In [306]: s1=pd.DataFrame({"a":["B","a","C"],"b":[1,2,3],"c":[2,3,4]}).set_index(
In [308]: s1.sort_index(level="a")Out[308]: ca b B 1 2C 3 4a 2 3In [309]: s1.sort_index(level="a",key=lambdaidx:idx.str.lower())Out[309]:
For information on key sorting by value, see value sorting.
By values
The Series.sort_values() method is used to sort a Series by its values. The
DataFrame.sort_values() method is used to sort a DataFrame by its column or row values.
The optional by parameter to DataFrame.sort_values() may used to specify one or more columns
to use to determine the sorted order.
By indexes and values
Strings passed as the by parameter to DataFrame.sort_values() may
refer to either columns or index level names.
In [327]: ser=pd.Series([1,2,3])In [328]: ser.searchsorted([
smallest / largest values
Series has the nsmallest() and nlargest() methods which return the
smallest or largest n values. For a large Series this can be much
faster than sorting the entire Series and calling head(n) on the result.
Sorting by a MultiIndex column
You must be explicit about sorting when the column is a MultiIndex, and fully specify
all levels to by.
In [344]: df1.columns=pd.MultiIndex.from_tuples( .....: [("a","one"),("a","two"),("b","three")]
Copying
The copy() method on pandas objects copies the underlying data (though not
the axis indexes, since they are immutable) and returns a new object. Note that
it is seldom necessary to copy objects. For example, there are only a
handful of ways to alter a DataFrame in-place:
Inserting, deleting, or modifying a column.
Assigning to the index or columns attributes.
For homogeneous data, directly modifying the values via the values
attribute or advanced indexing.
To be clear, no pandas method has the side effect of modifying your data;
almost every method returns a new object, leaving the original object
untouched. If the data is modified, it is because you did so explicitly.
dtypes
For the most part, pandas uses NumPy arrays and dtypes for Series or individual
columns of a DataFrame. NumPy provides support for float,
int, bool, timedelta64[ns] and datetime64[ns] (note that NumPy
does not support timezone-aware datetimes).
pandas and third-party libraries extend NumPy’s type system in a few places.
This section describes the extensions pandas has made internally.
See Extension types for how to write your own extension that
works with pandas. See the ecosystem page for a list of third-party
libraries that have implemented an extension.
The following table lists all of pandas extension types. For methods requiring dtype
arguments, strings can be specified as indicated. See the respective
documentation sections for more on each type.
Finally, arbitrary objects may be stored using the object dtype, but should
be avoided to the extent possible (for performance and interoperability with
other libraries and methods. See object conversion).
A convenient dtypes attribute for DataFrame returns a Series
with the data type of each column.
In [349]: dft["A"].dtypeOut[349]: dtype('float64')
If a pandas object contains data with multiple dtypes in a single column, the
dtype of the column will be chosen to accommodate all of the data types
(object is the most general).
# these ints are coerced to floatsIn [350]: pd.Series([1,2,3,4,5,6.0])Out[350]: 0 1.01 2.02 3.03 4.04 5.05 6.0dtype: float64# string data forces an ``object`` dtypeIn [351]: pd.Series([1,2,
The number of columns of each type in a DataFrame can be found by calling
DataFrame.dtypes.value_counts().
Numeric dtypes will propagate and can coexist in DataFrames.
If a dtype is passed (either directly via the dtype keyword, a passed ndarray,
or a passed Series), then it will be preserved in DataFrame operations. Furthermore,
different numeric dtypes will NOT be combined. The following example will give you a taste.
By default integer types are int64 and float types are float64,
regardless of platform (32-bit or 64-bit).
The following will all result in int64 dtypes.
In [359]: pd.DataFrame([1,2],columns=["a"]).dtypesOut[359]: a int64dtype: objectIn [360]: pd
upcasting
Types can potentially be upcasted when combined with other types, meaning they are promoted
from the current type (e.g. int to float).
In [363]: df3=df1.reindex_like(df2).fillna(value=0.0)+df2In [364]: df3Out[364]: A B C0 1.047606 0.256090 26.01 3.497968 1.426469 86.0
astype
You can use the astype() method to explicitly convert dtypes from one to another. These will by default return a copy,
even if the dtype was unchanged (pass copy=False to change this behavior). In addition, they will raise an
exception if the astype operation is invalid.
Upcasting is always according to the NumPy rules. If two different dtypes are involved in an operation,
then the more general one will be used as the result of the operation.
In [367]: df3Out[367]: A B C0 1.047606 0.256090 26.01 3.497968 1.426469 86.02 -0.150862 -0.416203 46.03 0.724370 1.139976 212.04 -1.203098 -1.193477 26.05 1.346426 0.096706 7.06 -0.052599 -1.956850 184.07 -0.756495 -0.714337 206.0
object conversion
pandas offers various functions to try to force conversion of types from the object dtype to other types.
In cases where the data is already of the correct type, but stored in an object array, the
DataFrame.infer_objects() and Series.infer_objects() methods can be used to soft convert
to the correct type.
In [382]: importdatetimeIn [383]:
gotchas
Performing selection operations on integer type data can easily upcast the data to floating.
The dtype of the input data will be preserved in cases where nans are not introduced.
See also Support for integer NA.
In [417]: dfi=df3.astype("int32")In [418]: dfi["E"]=1In [419]: dfi
Selecting columns based on dtype
The select_dtypes() method implements subsetting of columns
based on their dtype.
First, let’s create a DataFrame with a slew of different
dtypes:
select_dtypes() has two parameters include and exclude that allow you to
say “give me the columns with these dtypes” (include) and/or “give the
columns without these dtypes” (exclude).
These operations produce a pandas object of the same type as the left-hand-side
input that is of dtype bool. These boolean objects can be used in
indexing operations, see the section on Boolean indexing.
)
.
all
()
Out[50]:
one False
two True
three False
dtype: bool
In [51]:
(
df
>
0
)
.
any
()
Out[51]:
one True
two True
three True
dtype: bool
You can reduce to a final boolean value.
In [52]: (df>0).any().any()Out[52]: True
You can test if a pandas object is empty, via the empty property.
In [53]: df.emptyOut[53]: FalseIn [54]: pd.DataFrame(columns=list("ABC")).emptyOut[54]: True
c True True True
d False True True
In [58]:
(
df
+
df
==
df
*
2
)
.
all
()
Out[58]:
one False
two True
three False
dtype: bool
Notice that the boolean DataFrame df+df==df*2 contains some False values!
This is because NaNs do not compare as equals:
In [59]: np.nan==np.nanOut[59]: False
So, NDFrames (such as Series and DataFrames)
have an equals() method for testing equality, with NaNs in
corresponding locations treated as equal.
In [60]: (df+df).equals(df*2)Out[60]: True
Note that the Series or DataFrame index needs to be in the same order for
equality to be True:
Trying to compare Index or Series objects of different lengths will
raise a ValueError:
In [69]: pd.Series(['foo','bar','baz'])==pd.Series(['foo','bar'])---------------------------------------------------------------------------ValueErrorTraceback (most recent call last)
CellIn[69],line1----> 1pd.Series(['foo','bar','baz'])==pd.Series(['foo','bar'])File ~/work/pandas/pandas/pandas/core/ops/common.py:76, in _unpack_zerodim_and_defer.<locals>.new_method(self, other)72returnNotImplemented74other=item_from_zerodim(other)---> 76returnmethod(self,other)File ~/work/pandas/pandas/pandas/core/arraylike.py:40, in OpsMixin.__eq__(self, other)38@unpack_zerodim_and_defer("__eq__")39def__eq__(self,other):---> 40returnself._cmp_method(other,operator.eq)File ~/work/pandas/pandas/pandas/core/series.py:6133, in Series._cmp_method(self, other, op)6130res_name=ops.get_op_result_name(self,other)6132ifisinstance(other,Series)andnotself._indexed_same(other):-> 6133raiseValueError("Can only compare identically-labeled Series objects")6135lvalues=self._values6136rvalues=extract_array(other,extract_numpy=True,extract_range=True)ValueError: Can only compare identically-labeled Series objects
In [70]: pd.Series(['foo','bar','baz'])==pd.Series(['foo'])---------------------------------------------------------------------------ValueErrorTraceback (most recent call last)
CellIn[70],line1----> 1pd.Series(['foo','bar','baz'])==pd.Series(['foo'])File ~/work/pandas/pandas/pandas/core/ops/common.py:76, in _unpack_zerodim_and_defer.<locals>.new_method(self, other)72returnNotImplemented74other=item_from_zerodim(other)---> 76returnmethod(self,other)File ~/work/pandas/pandas/pandas/core/arraylike.py:40, in OpsMixin.__eq__(self, other)38@unpack_zerodim_and_defer("__eq__")39def__eq__(self,other):---> 40returnself._cmp_method(other,operator.eq)File ~/work/pandas/pandas/pandas/core/series.py:6133, in Series._cmp_method(self, other, op)6130res_name=ops.get_op_result_name(self,other)6132ifisinstance(other,Series)andnotself._indexed_same(other):-> 6133raiseValueError("Can only compare identically-labeled Series objects")6135lvalues=self._values6136rvalues=extract_array(other,extract_numpy=True,extract_range=True)ValueError: Can only compare identically-labeled Series objects
Note that on a mixed-type DataFrame object, describe() will
restrict the summary to include only numerical columns or, if none are, only
categorical columns:
This behavior can be controlled by providing a list of types as include/exclude
arguments. The special value all can also be used:
In [105]: frame.describe(include=["object"])Out[105]: acount 4unique 2top Yesfreq 2In [106]: frame.describe(include=["number"])Out[106]: bcount 4.000000mean 1.500000std 1.290994min 0.00000025% 0.75000050% 1.50000075% 2.250000max 3.000000In [107]: frame.describe(include="all")Out[107]: a bcount 4 4.000000unique 2 NaNtop Yes NaNfreq 2 NaNmean NaN 1.500000std NaN 1.290994min NaN 0.00000025% NaN 0.75000050% NaN 1.50000075% NaN 2.250000max NaN 3.000000
That feature relies on select_dtypes. Refer to
there for details about accepted inputs.
Out[109]:
0 1.118076
1 -0.352051
2 -1.242883
3 -1.277155
4 -0.641184
dtype: float64
In [110]:
s1
.
idxmin
(),
s1
.
idxmax
()
Out[110]:
(3, 0)
In [111]:
df1
=
pd
.
DataFrame
(
np
.
random
.
randn
(
5
,
3
),
columns
=
[
"A"
,
"B"
,
"C"
])
In [112]:
df1
Out[112]:
A B C
0 -0.327863 -0.946180 -0.137570
1 -0.186235 -0.257213 -0.486567
2 -0.507027 -0.871259 -0.111110
3 2.000339 -2.430505 0.089759
4 -0.321434 -0.033695 0.096271
In [113]:
df1
.
idxmin
(
axis
=
0
)
Out[113]:
A 2
B 3
C 1
dtype: int64
In [114]:
df1
.
idxmax
(
axis
=
1
)
Out[114]:
0 C
1 A
2 C
3 A
4 C
dtype: object
When there are multiple rows (or columns) matching the minimum or maximum
value, idxmin() and idxmax() return the first
matching index:
The value_counts() method can be used to count combinations across multiple columns.
By default all columns are used but a subset can be selected using the subset argument.
In [122]: data={"a":[1,2,3,4],"b":["x","x","y","y"]}In [123]: frame=pd.DataFrame(data)In [124]: frame.value_counts()Out[124]: a b1 x 12 x 13 y 14 y 1Name: count, dtype: int64
Similarly, you can get the most frequently occurring value(s), i.e. the mode, of the values in a Series or DataFrame:
In [125]: s5=pd.Series([1,1,3,3,3,5,5,7,7,7])In [126]: s5.mode()Out[126]: 0 31 7dtype: int64In [127]: df5=pd.DataFrame( .....: { .....: "A":np.random.randint(0,7,size=50), .....: "B":np.random.randint(-10,15,size=50), .....: } .....: ) .....: In [128]: df5.mode()Out[128]: A B0 1.0 -91 NaN 102 NaN 13
extract_city_name and add_country_name are functions taking and returning DataFrames.
Now compare the following:
In [143]: add_country_name(extract_city_name(df_p),country_name="US")Out[143]: city_and_code city_name city_and_country0 Chicago, IL Chicago ChicagoUS
Is equivalent to:
In [144]: df_p.pipe(extract_city_name).pipe(add_country_name,country_name="US")Out[144]: city_and_code city_name city_and_country0 Chicago, IL Chicago ChicagoUS
pandas encourages the second style, which is known as method chaining.
pipe makes it easy to use your own or another library’s functions
in method chains, alongside pandas’ methods.
In the example above, the functions extract_city_name and add_country_name each expected a DataFrame as the first positional argument.
What if the function you wish to apply takes its data as, say, the second argument?
In this case, provide pipe with a tuple of (callable,data_keyword).
.pipe will route the DataFrame to the argument specified in the tuple.
For example, we can fit a regression using statsmodels. Their API expects a formula first and a DataFrame as the second argument, data. We pass in the function, keyword pair (sm.ols,'data') to pipe:
The pipe method is inspired by unix pipes and more recently dplyr and magrittr, which
have introduced the popular (%>%) (read pipe) operator for R.
The implementation of pipe here is quite clean and feels right at home in Python.
We encourage you to view the source code of pipe().
df
.
apply
(
lambda
x
:
np
.
mean
(
x
),
axis
=
1
)
Out[146]:
a 1.583749
b 0.734929
c 1.133683
d -0.166914
dtype: float64
In [147]:
df
.
apply
(
lambda
x
:
x
.
max
()
-
x
.
min
())
Out[147]:
one 1.051928
two 1.632779
three 1.840607
dtype: float64
In [148]:
df
.
apply
(
np
.
cumsum
)
Out[148]:
one two three
a 1.394981 1.772517 NaN
b 1.738035 3.684640 -0.050390
c 2.433281 5.163008 1.177045
d NaN 5.442353 0.563873
In [149]:
df
.
apply
(
np
.
exp
)
Out[149]:
one two three
a 4.034899 5.885648 NaN
b 1.409244 6.767440 0.950858
c 2.004201 4.385785 3.412466
d NaN 1.322262 0.541630
The apply() method will also dispatch on a string method name.
In [150]: df.apply("mean")Out[150]: one 0.811094two 1.360588three 0.187958dtype: float64In [151]: df.apply("mean",axis=1)Out[151]: a 1.583749b 0.734929c 1.133683d -0.166914dtype: float64
The return type of the function passed to apply() affects the
type of the final output from DataFrame.apply for the default behaviour:
If the applied function returns a Series, the final output is a DataFrame.
The columns match the index of the Series returned by the applied function.
If the applied function returns any other type, the final output is a Series.
This default behaviour can be overridden using the result_type, which
accepts three options: reduce, broadcast, and expand.
These will determine how list-likes return values expand (or not) to a DataFrame.
apply() combined with some cleverness can be used to answer many questions
about a data set. For example, suppose we wanted to extract the date where the
maximum value for each column occurred:
In [152]: tsdf=pd.DataFrame( .....: np.random.randn(1000,3), .....: columns=["A","B","C"], .....: index=pd.date_range("1/1/2000",periods=1000), .....: ) .....: In [153]: tsdf.apply(lambdax:x.idxmax())Out[153]: A 2000-08-06B 2001-01-18C 2001-07-18dtype: datetime64[ns]
You may also pass additional arguments and keyword arguments to the apply()
method.
In [154]: defsubtract_and_divide(x,sub,divide=1): .....: return(x-sub)/divide .....: In [155]: df_udf=pd.DataFrame(np.ones((2,2)))In [156]: df_udf.apply(subtract_and_divide,args=(5,),divide=3)Out[156]: 0 10 -1.333333 -1.3333331 -1.333333 -1.333333
Another useful feature is the ability to pass Series methods to carry out some
Series operation on each column or row:
In [157]: tsdf=pd.DataFrame( .....: np.random.randn(10,3), .....: columns=["A","B","C"], .....: index=pd.date_range("1/1/2000",periods=10), .....: ) .....: In [158]: tsdf.iloc[3:7]=np.nanIn [159]: tsdfOut[159]: A B C2000-01-01 -0.158131 -0.232466 0.3216042000-01-02 -1.810340 -3.105758 0.4338342000-01-03 -1.209847 -1.156793 -0.1367942000-01-04 NaN NaN NaN2000-01-05 NaN NaN NaN2000-01-06 NaN NaN NaN2000-01-07 NaN NaN NaN2000-01-08 -0.653602 0.178875 1.0082982000-01-09 1.007996 0.462824 0.2544722000-01-10 0.307473 0.600337 1.643950In [160]: tsdf.apply(pd.Series.interpolate)Out[160]: A B C2000-01-01 -0.158131 -0.232466 0.3216042000-01-02 -1.810340 -3.105758 0.4338342000-01-03 -1.209847 -1.156793 -0.1367942000-01-04 -1.098598 -0.889659 0.0922252000-01-05 -0.987349 -0.622526 0.3212432000-01-06 -0.876100 -0.355392 0.5502622000-01-07 -0.764851 -0.088259 0.7792802000-01-08 -0.653602 0.178875 1.0082982000-01-09 1.007996 0.462824 0.2544722000-01-10 0.307473 0.600337 1.643950
Finally, apply() takes an argument raw which is False by default, which
converts each row or column into a Series before applying the function. When
set to True, the passed function will instead receive an ndarray object, which
has positive performance implications if you do not need the indexing
functionality.
.
DataFrame
(
.....:
np
.
random
.
randn
(
10
,
3
),
.....:
columns
=
[
"A"
,
"B"
,
"C"
],
.....:
index
=
pd
.
date_range
(
"1/1/2000"
,
periods
=
10
),
.....:
)
.....:
In [162]:
tsdf
.
iloc
[
3
:
7
]
=
np
.
nan
In [163]:
tsdf
Out[163]:
A B C
2000-01-01 1.257606 1.004194 0.167574
2000-01-02 -0.749892 0.288112 -0.757304
2000-01-03 -0.207550 -0.298599 0.116018
2000-01-04 NaN NaN NaN
2000-01-05 NaN NaN NaN
2000-01-06 NaN NaN NaN
2000-01-07 NaN NaN NaN
2000-01-08 0.814347 -0.257623 0.869226
2000-01-09 -0.250663 -1.206601 0.896839
2000-01-10 2.169758 -1.333363 0.283157
Using a single function is equivalent to apply(). You can also
pass named methods as strings. These will return a Series of the aggregated
output:
In [164]: tsdf.agg(lambdax:np.sum(x))Out[164]: A 3.033606B -1.803879C 1.575510dtype: float64In [165]: tsdf.agg("sum")Out[165]: A 3.033606B -1.803879C 1.575510dtype: float64# these are equivalent to a ``.sum()`` because we are aggregating# on a single functionIn [166]: tsdf.sum()Out[166]: A 3.033606B -1.803879C 1.575510dtype: float64
Single aggregations on a Series this will return a scalar value:
In [167]: tsdf["A"].agg("sum")Out[167]: 3.033606102414146
Aggregating with multiple functions
You can pass multiple aggregation arguments as a list.
The results of each of the passed functions will be a row in the resulting DataFrame.
These are naturally named from the aggregation function.
In [168]: tsdf.agg(["sum"])Out[168]: A B Csum 3.033606 -1.803879 1.57551
Multiple functions yield multiple rows:
In [169]: tsdf.agg(["sum","mean"])Out[169]: A B Csum 3.033606 -1.803879 1.575510mean 0.505601 -0.300647 0.262585
On a Series, multiple functions return a Series, indexed by the function names:
In [170]: tsdf["A"].agg(["sum","mean"])Out[170]: sum 3.033606mean 0.505601Name: A, dtype: float64
Passing a lambda function will yield a <lambda> named row:
In [171]: tsdf["A"].agg(["sum",lambdax:x.mean()])Out[171]: sum 3.033606<lambda> 0.505601Name: A, dtype: float64
Passing a named function will yield that name for the row:
In [172]: defmymean(x): .....: returnx.mean() .....: In [173]: tsdf["A"].agg(["sum",mymean])Out[173]: sum 3.033606mymean 0.505601Name: A, dtype: float64
Aggregating with a dict
Passing a dictionary of column names to a scalar or a list of scalars, to DataFrame.agg
allows you to customize which functions are applied to which columns. Note that the results
are not in any particular order, you can use an OrderedDict instead to guarantee ordering.
In [174]: tsdf.agg({"A":"mean","B":"sum"})Out[174]: A 0.505601B -1.803879dtype: float64
Passing a list-like will generate a DataFrame output. You will get a matrix-like output
of all of the aggregators. The output will consist of all unique functions. Those that are
not noted for a particular column will be NaN:
In [175]: tsdf.agg({"A":["mean","min"],"B":"sum"})Out[175]: A Bmean 0.505601 NaNmin -0.749892 NaNsum NaN -1.803879
Custom describe
With .agg() it is possible to easily create a custom describe function, similar
to the built in describe function.
Transform the entire frame. .transform() allows input functions as: a NumPy function, a string
function name or a user defined function.
In [185]: tsdf.transform(np.abs)Out[185]: A B C2000-01-01 0.428759 0.864890 0.6753412000-01-02 0.168731 1.338144 1.2793212000-01-03 1.621034 0.438107 0.9037942000-01-04 NaN NaN NaN2000-01-05 NaN NaN NaN2000-01-06 NaN NaN NaN2000-01-07 NaN NaN NaN2000-01-08 0.254374 1.240447 0.2010522000-01-09 0.157795 0.791197 1.1442092000-01-10 0.030876 0.371900 0.061932In [186]: tsdf.transform("abs")Out[186]: A B C2000-01-01 0.428759 0.864890 0.6753412000-01-02 0.168731 1.338144 1.2793212000-01-03 1.621034 0.438107 0.9037942000-01-04 NaN NaN NaN2000-01-05 NaN NaN NaN2000-01-06 NaN NaN NaN2000-01-07 NaN NaN NaN2000-01-08 0.254374 1.240447 0.2010522000-01-09 0.157795 0.791197 1.1442092000-01-10 0.030876 0.371900 0.061932In [187]: tsdf.transform(lambdax:x.abs())Out[187]: A B C2000-01-01 0.428759 0.864890 0.6753412000-01-02 0.168731 1.338144 1.2793212000-01-03 1.621034 0.438107 0.9037942000-01-04 NaN NaN NaN2000-01-05 NaN NaN NaN2000-01-06 NaN NaN NaN2000-01-07 NaN NaN NaN2000-01-08 0.254374 1.240447 0.2010522000-01-09 0.157795 0.791197 1.1442092000-01-10 0.030876 0.371900 0.061932
Here transform() received a single function; this is equivalent to a ufunc application.
In [188]: np.abs(tsdf)Out[188]: A B C2000-01-01 0.428759 0.864890 0.6753412000-01-02 0.168731 1.338144 1.2793212000-01-03 1.621034 0.438107 0.9037942000-01-04 NaN NaN NaN2000-01-05 NaN NaN NaN2000-01-06 NaN NaN NaN2000-01-07 NaN NaN NaN2000-01-08 0.254374 1.240447 0.2010522000-01-09 0.157795 0.791197 1.1442092000-01-10 0.030876 0.371900 0.061932
Passing a single function to .transform() with a Series will yield a single Series in return.
In [189]: tsdf["A"].transform(np.abs)Out[189]: 2000-01-01 0.4287592000-01-02 0.1687312000-01-03 1.6210342000-01-04 NaN2000-01-05 NaN2000-01-06 NaN2000-01-07 NaN2000-01-08 0.2543742000-01-09 0.1577952000-01-10 0.030876Freq: D, Name: A, dtype: float64
Transform with multiple functions
Passing multiple functions will yield a column MultiIndexed DataFrame.
The first level will be the original frame column names; the second level
will be the names of the transforming functions.
In [190]: tsdf.transform([np.abs,lambdax:x+1])Out[190]: A B C absolute <lambda> absolute <lambda> absolute <lambda>2000-01-01 0.428759 0.571241 0.864890 0.135110 0.675341 0.3246592000-01-02 0.168731 0.831269 1.338144 2.338144 1.279321 -0.2793212000-01-03 1.621034 -0.621034 0.438107 1.438107 0.903794 1.9037942000-01-04 NaN NaN NaN NaN NaN NaN2000-01-05 NaN NaN NaN NaN NaN NaN2000-01-06 NaN NaN NaN NaN NaN NaN2000-01-07 NaN NaN NaN NaN NaN NaN2000-01-08 0.254374 1.254374 1.240447 -0.240447 0.201052 0.7989482000-01-09 0.157795 0.842205 0.791197 1.791197 1.144209 -0.1442092000-01-10 0.030876 0.969124 0.371900 1.371900 0.061932 1.061932
Passing multiple functions to a Series will yield a DataFrame. The
resulting column names will be the transforming functions.
In [191]: tsdf["A"].transform([np.abs,lambdax:x+1])Out[191]: absolute <lambda>2000-01-01 0.428759 0.5712412000-01-02 0.168731 0.8312692000-01-03 1.621034 -0.6210342000-01-04 NaN NaN2000-01-05 NaN NaN2000-01-06 NaN NaN2000-01-07 NaN NaN2000-01-08 0.254374 1.2543742000-01-09 0.157795 0.8422052000-01-10 0.030876 0.969124
Transforming with a dict
Passing a dict of functions will allow selective transforming per column.
In [192]: tsdf.transform({"A":np.abs,"B":lambdax:x+1})Out[192]: A B2000-01-01 0.428759 0.1351102000-01-02 0.168731 2.3381442000-01-03 1.621034 1.4381072000-01-04 NaN NaN2000-01-05 NaN NaN2000-01-06 NaN NaN2000-01-07 NaN NaN2000-01-08 0.254374 -0.2404472000-01-09 0.157795 1.7911972000-01-10 0.030876 1.371900
Passing a dict of lists will generate a MultiIndexed DataFrame with these
selective transforms.
In [193]: tsdf.transform({"A":np.abs,"B":[lambdax:x+1,"sqrt"]})Out[193]: A B absolute <lambda> sqrt2000-01-01 0.428759 0.135110 NaN2000-01-02 0.168731 2.338144 1.1567822000-01-03 1.621034 1.438107 0.6618972000-01-04 NaN NaN NaN2000-01-05 NaN NaN NaN2000-01-06 NaN NaN NaN
d NaN 0.279344 -0.613172
In [196]:
def
f
(
x
):
.....:
return
len
(
str
(
x
))
.....:
In [197]:
df4
[
"one"
]
.
map
(
f
)
Out[197]:
a 18
b 19
c 18
d 3
Name: one, dtype: int64
In [198]:
df4
.
map
(
f
)
Out[198]:
one two three
a 18 17 3
b 19 18 20
c 18 18 16
d 3 19 19
Series.map() has an additional feature; it can be used to easily
“link” or “map” values defined by a secondary series. This is closely related
to merging/joining functionality:
In [199]: s=pd.Series( .....: ["six","seven","six","seven","six"],index=["a","b","c","d","e"] .....: ) .....: In [200]: t=pd.Series({"six":6.0,"seven":7.0})In [201]: sOut[201]: a sixb sevenc sixd sevene sixdtype: objectIn [202]: s.map(t)Out[202]: a 6.0b 7.0c 6.0d 7.0e 6.0dtype: float64
f NaN NaN NaN
b -0.050390 1.912123 0.343054
three two one
a NaN 1.772517 1.394981
b -0.050390 1.912123 0.343054
c 1.227435 1.478369 0.695246
d -0.613172 0.279344 NaN
df3
=
df2
-
df2
.
mean
()
In [215]:
df2
Out[215]:
one two
a 1.394981 1.772517
b 0.343054 1.912123
c 0.695246 1.478369
In [216]:
df3
Out[216]:
one two
a 0.583888 0.051514
b -0.468040 0.191120
c -0.115848 -0.242634
In [217]:
df
.
reindex_like
(
df2
)
Out[217]:
one two
a 1.394981 1.772517
b 0.343054 1.912123
c 0.695246 1.478369
join='inner'
It returns a tuple with both of the reindexed Series:
In [218]: s=pd.Series(np.random.randn(5),index=["a","b","c","d","e"])In [219]: s1=s[:4]In [220]: s2=s[1:]In [221]: s1.align(s2)Out[221]: (a -0.186646 b -1.692424 c -0.303893 d -1.425662 e NaN dtype: float64, a NaN b -1.692424 c -0.303893 d -1.425662 e 1.114285 dtype: float64)In [222]: s1.align(s2,join="inner")Out[222]: (b -1.692424 c -0.303893 d -1.425662 dtype: float64, b -1.692424 c -0.303893 d -1.425662 dtype: float64)In [223]: s1.align(s2,join="left")Out[223]: (a -0.186646 b -1.692424 c -0.303893 d -1.425662 dtype: float64, a NaN b -1.692424 c -0.303893 d -1.425662 dtype: float64)
For DataFrames, the join method will be applied to both the index and the
columns by default:
In [224]: df.align(df2,join="inner")Out[224]: ( one two a 1.394981 1.772517 b 0.343054 1.912123 c 0.695246 1.478369, one two a 1.394981 1.772517 b 0.343054 1.912123 c 0.695246 1.478369)
You can also pass an axis option to only align on the specified axis:
In [225]: df.align(df2,join="inner",axis=0)Out[225]: ( one two three a 1.394981 1.772517 NaN b 0.343054 1.912123 -0.050390 c 0.695246 1.478369 1.227435, one two a 1.394981 1.772517 b 0.343054 1.912123 c 0.695246 1.478369)
If you pass a Series to DataFrame.align(), you can choose to align both
objects either on the DataFrame’s index or columns using the axis argument:
In [226]: df.align(df2.iloc[0],axis=1)Out[226]: ( one three two a 1.394981 NaN 1.772517 b 0.343054 -0.050390 1.912123 c 0.695246 1.227435 1.478369 d NaN -0.613172 0.279344, one 1.394981 three NaN two 1.772517 Name: a, dtype: float64)
Fill values backward
nearest
Fill from the nearest index value
We illustrate these fill methods on a simple Series:
reindex() will raise a ValueError if the index is not monotonically
increasing or decreasing. fillna() and interpolate()
will not perform any checks on the order of the index.
2000-01-07 2.395489
2000-01-08 NaN
2000-01-09 0.733639
2000-01-10 0.733639
Freq: D, dtype: float64
In contrast, tolerance specifies the maximum distance between the index and
indexer values:
Notice that when used on a DatetimeIndex, TimedeltaIndex or
PeriodIndex, tolerance will coerced into a Timedelta if possible.
This allows you to specify tolerance with appropriate strings.
0
)
Out[240]:
one two three
b 0.343054 1.912123 -0.050390
c 0.695246 1.478369 1.227435
In [241]:
df
.
drop
([
"one"
],
axis
=
1
)
Out[241]:
two three
a 1.772517 NaN
b 1.912123 -0.050390
c 1.478369 1.227435
d 0.279344 -0.613172
Note that the following also works, but is a bit less obvious / clean:
In [242]: df.reindex(df.index.difference(["a","d"]))Out[242]: one two threeb 0.343054 1.912123 -0.050390c 0.695246 1.478369 1.227435
D -1.425662
E 1.114285
dtype: float64
If you pass a function, it must return a value when called with any of the
labels (and must produce a set of unique values). A dict or
Series can also be used:
In [245]: df.rename( .....: columns={"one":"foo","two":"bar"}, .....: index={"a":"apple","b":"banana","d":"durian"}, .....: ) .....: Out[245]: foo bar threeapple 1.394981 1.772517 NaNbanana 0.343054 1.912123 -0.050390c 0.695246 1.478369 1.227435durian NaN 0.279344 -0.613172
If the mapping doesn’t include a column/index label, it isn’t renamed. Note that
extra labels in the mapping don’t throw an error.
DataFrame.rename() also supports an “axis-style” calling convention, where
you specify a single mapper and the axis to apply that mapping to.
In [246]: df.rename({"one":"foo","two":"bar"},axis="columns")Out[246]: foo bar threea 1.394981 1.772517 NaNb 0.343054 1.912123 -0.050390c 0.695246 1.478369 1.227435d NaN 0.279344 -0.613172In [247]: df.rename({"a":"apple","b":"banana","d":"durian"},axis="index")Out[247]: one two threeapple 1.394981 1.772517 NaNbanana 0.343054 1.912123 -0.050390c 0.695246 1.478369 1.227435durian NaN 0.279344 -0.613172
Finally, rename() also accepts a scalar or list-like
for altering the Series.name attribute.
In [248]: s.rename("scalar-name")Out[248]: a -0.186646b -1.692424c -0.303893d -1.425662e 1.114285Name: scalar-name, dtype: float64
key will be given the Series of values and should return a Series
or array of the same shape with the transformed values. For DataFrame objects,
the key is applied per column, so the key should still expect a Series and return
a Series, e.g.
In [319]: df=pd.DataFrame({"a":["B","a","C"],"b":[1,2,3]})
In [320]: df.sort_values(by="a")Out[320]: a b0 B 12 C 31 a 2In [321]: df.sort_values(by="a",key=lambdacol:col.str.lower())Out[321]: a b1 a 20 B 12 C 3
The name or type of each column can be used to apply different functions to
different columns.
),
(
"a"
,
2
),
(
"b"
,
2
),
(
"b"
,
1
),
(
"b"
,
1
)]
.....:
)
.....:
In [323]:
idx
.
names
=
[
"first"
,
"second"
]
# Build DataFrame
In [324]:
df_multi
=
pd
.
DataFrame
({
"A"
:
np
.
arange
(
6
,
0
,
-
1
)},
index
=
idx
)
In [325]:
df_multi
Out[325]:
A
first second
a 1 6
2 5
2 4
b 2 3
1 2
1 1
Sort by ‘second’ (index) and ‘A’ (column)
In [326]: df_multi.sort_values(by=["second","A"])Out[326]: Afirst second b 1 1 1 2a 1 6b 2 3a 2 4 2 5
0
,
3
])
Out[328]:
array([0, 2])
In [329]:
ser
.
searchsorted
([
0
,
4
])
Out[329]:
array([0, 3])
In [330]:
ser
.
searchsorted
([
1
,
3
],
side
=
"right"
)
Out[330]:
array([1, 3])
In [331]:
ser
.
searchsorted
([
1
,
3
],
side
=
"left"
)
Out[331]:
array([0, 2])
In [332]:
ser
=
pd
.
Series
([
3
,
1
,
2
])
In [333]:
ser
.
searchsorted
([
0
,
3
],
sorter
=
np
.
argsort
(
ser
))
Out[333]:
array([0, 2])
In [334]:
s
=
pd
.
Series
(
np
.
random
.
permutation
(
10
))
In [335]:
s
Out[335]:
0 2
1 0
2 3
3 7
4 1
5 5
6 9
7 6
8 8
9 4
dtype: int64
In [336]:
s
.
sort_values
()
Out[336]:
1 0
4 1
0 2
2 3
9 4
5 5
7 6
3 7
8 8
6 9
dtype: int64
In [337]:
s
.
nsmallest
(
3
)
Out[337]:
1 0
4 1
0 2
dtype: int64
In [338]:
s
.
nlargest
(
3
)
Out[338]:
6 9
8 8
3 7
dtype: int64
DataFrame also has the nlargest and nsmallest methods.
In [339]: df=pd.DataFrame( .....: { .....: "a":[-2,-1,1,10,8,11,-1], .....: "b":list("abdceff"), .....: "c":[1.0,2.0,4.0,3.2,np.nan,3.0,4.0], .....: } .....: ) .....: In [340]: df.nlargest(3,"a")Out[340]: a b c5 11 f 3.03 10 c 3.24 8 e NaNIn [341]: df.nlargest(5,["a","c"])Out[341]: a b c5 11 f 3.03 10 c 3.24 8 e NaN2 1 d 4.06 -1 f 4.0In [342]: df.nsmallest(3,"a")Out[342]: a b c0 -2 a 1.01 -1 b 2.06 -1 f 4.0In [343]: df.nsmallest(5,["a","c"])Out[343]: a b c0 -2 a 1.01 -1 b 2.06 -1 f 4.02 1 d 4.04 8 e NaN
Note that Numpy will choose platform-dependent types when creating arrays.
The following WILL result in int32 on 32-bit platform.
In [362]: frame=pd.DataFrame(np.array([1,2]))
2 -0.150862 -0.416203 46.0
3 0.724370 1.139976 212.0
4 -1.203098 -1.193477 26.0
5 1.346426 0.096706 7.0
6 -0.052599 -1.956850 184.0
7 -0.756495 -0.714337 206.0
In [365]:
df3
.
dtypes
Out[365]:
A float32
B float64
C float64
dtype: object
DataFrame.to_numpy() will return the lower-common-denominator of the dtypes, meaning
the dtype that can accommodate ALL of the types in the resulting homogeneous dtyped NumPy array. This can
force some upcasting.
In [366]: df3.to_numpy().dtypeOut[366]: dtype('float64')
In [368]:
df3
.
dtypes
Out[368]:
A float32
B float64
C float64
dtype: object
# conversion of dtypes
In [369]:
df3
.
astype
(
"float32"
)
.
dtypes
Out[369]:
A float32
B float32
C float32
dtype: object
Convert a subset of columns to a specified type using astype().
In [370]: dft=pd.DataFrame({"a":[1,2,3],"b":[4,5,6],"c":[7,8,9]})In [371]: dft[["a","b"]]=dft[["a","b"]].astype(np.uint8)In [372]: dftOut[372]: a b c0 1 4 71 2 5 82 3 6 9In [373]: dft.dtypesOut[373]: a uint8b uint8c int64dtype: object
Convert certain columns to a specific dtype by passing a dict to astype().
In [374]: dft1=pd.DataFrame({"a":[1,0,1],"b":[4,5,6],"c":[7,8,9]})In [375]: dft1=dft1.astype({"a":np.bool_,"c":np.float64})In [376]: dft1Out[376]: a b c0 True 4 7.01 False 5 8.02 True 6 9.0In [377]: dft1.dtypesOut[377]: a boolb int64c float64dtype: object
df
=
pd
.
DataFrame
(
.....:
[
.....:
[
1
,
2
],
.....:
[
"a"
,
"b"
],
.....:
[
datetime
.
datetime
(
2016
,
3
,
2
),
datetime
.
datetime
(
2016
,
3
,
2
)],
.....:
]
.....:
)
.....:
In [384]:
df
=
df
.
T
In [385]:
df
Out[385]:
0 1 2
0 1 a 2016-03-02 00:00:00
1 2 b 2016-03-02 00:00:00
In [386]:
df
.
dtypes
Out[386]:
0 object
1 object
2 object
dtype: object
Because the data was transposed the original inference stored all columns as object, which
infer_objects will correct.
In [387]: df.infer_objects().dtypesOut[387]: 0 int641 object2 datetime64[ns]dtype: object
The following functions are available for one dimensional object arrays or scalars to perform
hard conversion of objects to a specified type:
In [393]: m=["5us",pd.Timedelta("1day")]In [394]: pd.to_timedelta(m)Out[394]: TimedeltaIndex(['0 days 00:00:00.000005', '1 days 00:00:00'], dtype='timedelta64[ns]', freq=None)
To force a conversion, we can pass in an errors argument, which specifies how pandas should deal with elements
that cannot be converted to desired dtype or object. By default, errors='raise', meaning that any errors encountered
will be raised during the conversion process. However, if errors='coerce', these errors will be ignored and pandas
will convert problematic elements to pd.NaT (for datetime and timedelta) or np.nan (for numeric). This might be
useful if you are reading in data which is mostly of the desired dtype (e.g. numeric, datetime), but occasionally has
non-conforming elements intermixed that you want to represent as missing:
In addition to object conversion, to_numeric() provides another argument downcast, which gives the
option of downcasting the newly (or already) numeric data to a smaller dtype, which can conserve memory:
In [402]: m=["1",2,3]In [403]: pd.to_numeric(m,downcast="integer")# smallest signed int dtypeOut[403]: array([1, 2, 3], dtype=int8)In [404]: pd.to_numeric(m,downcast="signed")# same as 'integer'Out[404]: array([1, 2, 3], dtype=int8)In [405]: pd.to_numeric(m,downcast="unsigned")# smallest unsigned int dtypeOut[405]: array([1, 2, 3], dtype=uint8)In [406]: pd.to_numeric(m,downcast="float")# smallest float dtypeOut[406]: array([1., 2., 3.], dtype=float32)
As these methods apply only to one-dimensional arrays, lists or scalars; they cannot be used directly on multi-dimensional objects such
as DataFrames. However, with apply(), we can “apply” the function over each column efficiently:
In [424]: dfa=df3.copy()In [425]: dfa["A"]=dfa["A"].astype("float32")In [426]: dfa.dtypesOut[426]: A float32B float64C float64dtype: objectIn [427]: casted=dfa[df2>0]In [428]: castedOut[428]: A B C0 1.047606 0.256090 26.01 3.497968 1.426469 86.02 NaN NaN 46.03 NaN 1.139976 212.04 NaN NaN 26.05 1.346426 0.096706 7.06 NaN NaN 184.07 NaN NaN 206.0In [429]: casted.dtypesOut[429]: A float32B float64C float64dtype: object
subs
]]
.....:
[[numpy.character, [numpy.bytes_, numpy.str_]],
[numpy.void, [numpy.record]]]],
numpy.bool_,
numpy.datetime64,
numpy.object_]]
1580
raise
ValueError
(
1581
f
"The truth value of a
{
type
(
self
)
.
__name__
}
is ambiguous. "
1582
"Use a.empty, a.bool(), a.item(), a.any() or a.all()."