We’ll start with a quick, non-comprehensive overview of the fundamental data
structures in pandas to get you started. The fundamental behavior about data
types, indexing, axis labeling, and alignment apply across all of the
objects. To get started, import NumPy and load pandas into your namespace:
In [1]: importnumpyasnpIn [2]: importpandasaspd
Fundamentally, data alignment is intrinsic. The link
between labels and data will not be broken unless done so explicitly by you.
We’ll give a brief intro to the data structures, then consider all of the broad
categories of functionality and methods in separate sections.
Series
Series is a one-dimensional labeled array capable of holding any data
type (integers, strings, floating point numbers, Python objects, etc.). The axis
labels are collectively referred to as the index. The basic method to create a Series is to call:
s=pd.Series(data,index=index)
Here, data can be many different things:
a Python dict
an ndarray
a scalar value (like 5)
The passed index is a list of axis labels. Thus, this separates into a few
cases depending on what data is:
From ndarray
If data is an ndarray, index must be the same length as data. If no
index is passed, one will be created having values [0,...,len(data)-1].
In [7]: d={"b":1,"a":0,"c":2}In [8]: pd.Series(d)Out[8]: b 1a 0c 2dtype: int64
If an index is passed, the values in data corresponding to the labels in the
index will be pulled out.
In [9]: d={"a":0.0,"b":1.0,"c":2.0}In [10]: pd.Series(d)Out[10]: a 0.0b 1.0c 2.0dtype: float64In [11]: pd.Series(d,index=["b","c","d","a"])Out[11]: b 1.0c 2.0d NaNa 0.0dtype: float64
From scalar value
If data is a scalar value, an index must be
provided. The value will be repeated to match the length of index.
In [12]: pd.Series(5.0,index=["a","b","c","d","e"])Out[12]: a 5.0b 5.0c 5.0d 5.0e 5.0dtype: float64
Series is ndarray-like
Series acts very similarly to a ndarray and is a valid argument to most NumPy functions.
However, operations such as slicing will also slice the index.
In [13]: s.iloc[0]Out[13]: 0.4691122999071863In [14]: s.iloc[:3]Out[14]: a 0.469112b -0.282863c -1.509059dtype: float64In [15]: s[s>s.median()]Out[15]: a 0.469112e 1.212112dtype: float64In [16]: s.iloc[[4,3,1]]Out[16]: e 1.212112d -1.135632b -0.282863dtype: float64In [17]: np.exp(s)Out[17]: a 1.598575b 0.753623c 0.221118d 0.321219e 3.360575dtype: float64
Like a NumPy array, a pandas Series has a single dtype.
In [18]: s.dtypeOut[18]: dtype('float64')
This is often a NumPy dtype. However, pandas and 3rd-party libraries
extend NumPy’s type system in a few places, in which case the dtype would
be an ExtensionDtype. Some examples within
pandas are Categorical data and Nullable integer data type. See dtypes
for more.
Accessing the array can be useful when you need to do some operation without the
index (to disable automatic alignment, for example).
Series.array will always be an ExtensionArray.
Briefly, an ExtensionArray is a thin wrapper around one or more concrete arrays like a
numpy.ndarray. pandas knows how to take an ExtensionArray and
store it in a Series or a column of a .
See for more.
If a label is not contained in the index, an exception is raised:
In [26]: s["f"]---------------------------------------------------------------------------KeyErrorTraceback (most recent call last)
File ~/work/pandas/pandas/pandas/core/indexes/base.py:3812, in Index.get_loc(self, key)3811try:-> 3812returnself._engine.get_loc(casted_key)3813exceptKeyErroraserr:File ~/work/pandas/pandas/pandas/_libs/index.pyx:167, in
in
in
in
: 'f'
Traceback (most recent call last)
in
in
in
: 'f'
Using the Series.get() method, a missing label will return None or specified default:
In [27]: s.get("f")In [28]: s.get("f",np.nan)Out[28]: nan
Vectorized operations and label alignment with Series
When working with raw NumPy arrays, looping through value-by-value is usually
not necessary. The same is true when working with Series in pandas.
Series can also be passed into most NumPy methods expecting an ndarray.
In [29]: s+sOut[29]: a 0.938225b -0.565727c -3.018117d -2.271265e 24.000000dtype: float64In [30]: s*2Out[30]: a 0.938225b -0.565727c -3.018117d -2.271265e 24.000000dtype: float64In [31]: np.exp(s)Out[31]: a 1.598575b 0.753623c 0.221118d 0.321219e 162754.791419dtype: float64
A key difference between Series and ndarray is that operations between Series
automatically align the data based on label. Thus, you can write computations
without giving consideration to whether the Series involved have the same
labels.
In [32]: s.iloc[1:]+s.iloc[:-1]Out[32]: a NaNb -0.565727c -3.018117d -2.271265e NaNdtype: float64
The result of an operation between unaligned Series will have the union of
the indexes involved. If a label is not found in one Series or the other, the
result will be marked as missing NaN. Being able to write code without doing
any explicit data alignment grants immense freedom and flexibility in
interactive data analysis and research. The integrated data alignment features
of the pandas data structures set pandas apart from the majority of related
tools for working with labeled data.
The Seriesname can be assigned automatically in many cases, in particular,
when selecting a single column from a DataFrame, the name will be assigned
the column label.
In [36]: s2=s.rename("different")In [37]: s2.nameOut[37]: 'different'
Note that s and s2 refer to different objects.
DataFrame
DataFrame is a 2-dimensional labeled data structure with columns of
potentially different types. You can think of it like a spreadsheet or SQL
table, or a dict of Series objects. It is generally the most commonly used
pandas object. Like Series, DataFrame accepts many different kinds of input:
Along with the data, you can optionally pass index (row labels) and
columns (column labels) arguments. If you pass an index and / or columns,
you are guaranteeing the index and / or columns of the resulting
DataFrame. Thus, a dict of Series plus a specific index will discard all data
not matching up to the passed index.
If axis labels are not passed, they will be constructed from the input data
based on common sense rules.
From dict of Series or dicts
The resulting index will be the union of the indexes of the various
Series. If there are any nested dicts, these will first be converted to
Series. If no columns are passed, the columns will be the ordered list of dict
keys.
In [38]: d={ ....: "one":pd.Series([1.0,2.0,3.0],index=["a","b","c"]), ....: "two"
From dict of ndarrays / lists
All ndarrays must share the same length. If an index is passed, it must
also be the same length as the arrays. If no index is passed, the
result will be range(n), where n is the array length.
In [45]: d={"one":[1.0,2.0,3.0,4.0],"two":[4.0,3.0,2.0,
From structured or record array
This case is handled identically to a dict of arrays.
In [48]: data=np.zeros((2,),dtype=[("A","i4"),("B","f4"),("C","a10")])In [49]: data[:]=[(1
From a list of dicts
In [53]: data2=[{"a":1,"b":2},{"a":5,"b":10,"c":20}]In [54]: pd.DataFrame(data2)
From a dict of tuples
You can automatically create a MultiIndexed frame by passing a tuples
dictionary.
In [57]: pd.DataFrame( ....: { ....: ("a","b"):{("A","B"):1,("A","C"):2}, ....: ("a"
From a Series
The result will be a DataFrame with the same index as the input Series, and
with one column whose name is the original name of the Series (only if no other
column name provided).
In [58]: ser=pd.Series(range(3),index=list("abc"),name="ser")In [59]: pd.DataFrame(ser)Out[59]:
From a list of namedtuples
The field names of the first namedtuple in the list determine the columns
of the DataFrame. The remaining namedtuples (or tuples) are simply unpacked
and their values are fed into the rows of the DataFrame. If any of those
tuples is shorter than the first namedtuple then the later columns in the
corresponding row are marked as missing values. If any are longer than the
first namedtuple, a ValueError is raised.
In [60]:
From a list of dataclasses
Data Classes as introduced in PEP557,
can be passed into the DataFrame constructor.
Passing a list of dataclasses is equivalent to passing a list of dictionaries.
Please be aware, that all values in the list should be dataclasses, mixing
types in the list would result in a TypeError.
In [65]: fromdataclassesimportmake_dataclassIn [66]: Point=make_dataclass("Point",[("x",int),("y",
Alternate constructors
DataFrame.from_dict
DataFrame.from_dict() takes a dict of dicts or a dict of array-like sequences
and returns a DataFrame. It operates like the DataFrame constructor except
for the orient parameter which is 'columns' by default, but which can be
set to 'index' in order to use the dict keys as row labels.
In [68]: pd.DataFrame.
Column selection, addition, deletion
You can treat a DataFrame semantically like a dict of like-indexed Series
objects. Getting, setting, and deleting columns works with the same syntax as
the analogous dict operations:
In [72]: df["one"]Out[72]: a 1.0b 2.0c 3.0d NaNName: one, dtype: float64In [73]: df["three"]
Assigning new columns in method chains
Inspired by dplyr’smutate verb, DataFrame has an assign()
method that allows you to easily create new columns that are potentially
derived from existing columns.
In [85]: iris=pd.read_csv("data/iris.data")In [86]: iris.head()Out[86]: SepalLength SepalWidth PetalLength PetalWidth Name
Indexing / selection
The basics of indexing are as follows:
Operation
Syntax
Result
Select column
df[col]
Series
Select row by label
Data alignment and arithmetic
Data alignment between DataFrame objects automatically align on both the
columns and the index (row labels). Again, the resulting object will have the
union of the column and row labels.
In [94]: df=pd.DataFrame(np.random.randn(10,4),columns=["A","B"
Transposing
To transpose, access the T attribute or DataFrame.transpose(),
similar to an ndarray:
# only show the first 5 rowsIn [107]: df[:5].TOut[107]: 0 1 2 3 4A 0.271860 -1.087401 0.524988 -1.039268 0.844885B -0.424972 -0.673690 0.404705 -0.370647 1.075770C 0.567020 0.113648 0.577046 -1.157892 -0.109050D 0.276232 -1.478427 -1.715002 -1.344312 1.643563
DataFrame interoperability with NumPy functions
Most NumPy functions can be called directly on Series and DataFrame.
In [108]: np.exp(df)Out[108]: A B C D0 1.312403 0.653788 1.763006 1.3181541 0.337092 0.509824 1.120358 0.2279962 1.690438 1.498861 1.780770 0.1799633 0.353713 0.690288 0.314148 0.2607194 2.327710 2.932249 0.896686 5.1735715 0.230066 1.429065 0.509360 0.169161
Console display
A very large DataFrame will be truncated to display them in the console.
You can also get a summary using info().
(The baseball dataset is from the plyr R package):
In [123]: baseball=pd.read_csv("data/baseball.csv")In [124]: print(baseball) id player year stint team lg ... so ibb hbp sh sf gidp
DataFrame column attribute access and IPython completion
If a DataFrame column label is a valid Python variable name, the column can be
accessed like an attribute:
In [135]: df=pd.DataFrame({"foo1":np.random.randn(5),"foo2":np.random.randn(
To construct a DataFrame with missing data, we use np.nan to
represent missing values. Alternatively, you may pass a numpy.MaskedArray
as the data argument to the DataFrame constructor, and its masked entries will
be considered missing. See Missing data for more.
from_dict
(
dict
([(
"A"
,
[
1
,
2
,
3
]),
(
"B"
,
[
4
,
5
,
6
])]))
Out[68]:
A B
0 1 4
1 2 5
2 3 6
If you pass orient='index', the keys will be the row labels. In this
case, you can also pass the desired column names:
In [69]: pd.DataFrame.from_dict( ....: dict([("A",[1,2,3]),("B",[4,5,6])]), ....: orient="index", ....: columns=["one","two","three"], ....: ) ....: Out[69]: one two threeA 1 2 3B 4 5 6
DataFrame.from_records
DataFrame.from_records() takes a list of tuples or an ndarray with structured
dtype. It works analogously to the normal DataFrame constructor, except that
the resulting DataFrame index may be a specific field of the structured
dtype.
In [70]: dataOut[70]: array([(1, 2., b'Hello'), (2, 3., b'World')], dtype=[('A', '<i4'), ('B', '<f4'), ('C', 'S10')])In [71]: pd.DataFrame.from_records(data,index="C")Out[71]: A BC b'Hello' 1 2.0b'World' 2 3.0
=
df
[
"one"
]
*
df
[
"two"
]
In [74]:
df
[
"flag"
]
=
df
[
"one"
]
>
2
In [75]:
df
Out[75]:
one two three flag
a 1.0 1.0 1.0 False
b 2.0 2.0 4.0 False
c 3.0 3.0 9.0 True
d NaN 4.0 NaN False
Columns can be deleted or popped like with a dict:
In [76]: deldf["two"]In [77]: three=df.pop("three")In [78]: dfOut[78]: one flaga 1.0 Falseb 2.0 Falsec 3.0 Trued NaN False
When inserting a scalar value, it will naturally be propagated to fill the
column:
In [79]: df["foo"]="bar"In [80]: dfOut[80]: one flag fooa 1.0 False barb 2.0 False barc 3.0 True bard NaN False bar
When inserting a Series that does not have the same index as the DataFrame, it
will be conformed to the DataFrame’s index:
In [81]: df["one_trunc"]=df["one"][:2]In [82]: dfOut[82]: one flag foo one_trunca 1.0 False bar 1.0b 2.0 False bar 2.0c 3.0 True bar NaNd NaN False bar NaN
You can insert raw ndarrays but their length must match the length of the
DataFrame’s index.
By default, columns get inserted at the end. DataFrame.insert()
inserts at a particular location in the columns:
In [83]: df.insert(1,"bar",df["one"])In [84]: dfOut[84]: one bar flag foo one_trunca 1.0 1.0 False bar 1.0b 2.0 2.0 False bar 2.0c 3.0 3.0 True bar NaNd NaN NaN False bar NaN
0 5.1 3.5 1.4 0.2 Iris-setosa
1 4.9 3.0 1.4 0.2 Iris-setosa
2 4.7 3.2 1.3 0.2 Iris-setosa
3 4.6 3.1 1.5 0.2 Iris-setosa
4 5.0 3.6 1.4 0.2 Iris-setosa
In [87]:
iris
.
assign
(
sepal_ratio
=
iris
[
"SepalWidth"
]
/
iris
[
"SepalLength"
])
.
head
()
Out[87]:
SepalLength SepalWidth PetalLength PetalWidth Name sepal_ratio
0 5.1 3.5 1.4 0.2 Iris-setosa 0.686275
1 4.9 3.0 1.4 0.2 Iris-setosa 0.612245
2 4.7 3.2 1.3 0.2 Iris-setosa 0.680851
3 4.6 3.1 1.5 0.2 Iris-setosa 0.673913
4 5.0 3.6 1.4 0.2 Iris-setosa 0.720000
In the example above, we inserted a precomputed value. We can also pass in
a function of one argument to be evaluated on the DataFrame being assigned to.
assign()always returns a copy of the data, leaving the original
DataFrame untouched.
Passing a callable, as opposed to an actual value to be inserted, is
useful when you don’t have a reference to the DataFrame at hand. This is
common when using assign() in a chain of operations. For example,
we can limit the DataFrame to just those observations with a Sepal Length
greater than 5, calculate the ratio, and plot:
Since a function is passed in, the function is computed on the DataFrame
being assigned to. Importantly, this is the DataFrame that’s been filtered
to those rows with sepal length greater than 5. The filtering happens first,
and then the ratio calculations. This is an example where we didn’t
have a reference to the filtered DataFrame available.
The function signature for assign() is simply **kwargs. The keys
are the column names for the new fields, and the values are either a value
to be inserted (for example, a Series or NumPy array), or a function
of one argument to be called on the DataFrame. A copy of the original
DataFrame is returned, with the new values inserted.
The order of **kwargs is preserved. This allows
for dependent assignment, where an expression later in **kwargs can refer
to a column created earlier in the same assign().
In [90]: dfa=pd.DataFrame({"A":[1,2,3],"B":[4,5,6]})In [91]: dfa.assign(C=lambdax:x["A"]+x["B"],D=lambdax:x["A"]+x["C"])Out[91]: A B C D0 1 4 5 61 2 5 7 92 3 6 9 12
In the second expression, x['C'] will refer to the newly created column,
that’s equal to dfa['A']+dfa['B'].
df.loc[label]
Series
Select row by integer location
df.iloc[loc]
Series
Slice rows
df[5:10]
DataFrame
Select rows by boolean vector
df[bool_vec]
DataFrame
Row selection, for example, returns a Series whose index is the columns of the
DataFrame:
In [92]: df.loc["b"]Out[92]: one 2.0bar 2.0flag Falsefoo barone_trunc 2.0Name: b, dtype: objectIn [93]: df.iloc[2]Out[93]: one 3.0bar 3.0flag Truefoo barone_trunc NaNName: c, dtype: object
For a more exhaustive treatment of sophisticated label-based indexing and
slicing, see the section on indexing. We will address the
fundamentals of reindexing / conforming to new sets of labels in the
section on reindexing.
,
"C"
,
"D"
])
In [95]:
df2
=
pd
.
DataFrame
(
np
.
random
.
randn
(
7
,
3
),
columns
=
[
"A"
,
"B"
,
"C"
])
In [96]:
df
+
df2
Out[96]:
A B C D
0 0.045691 -0.014138 1.380871 NaN
1 -0.955398 -1.501007 0.037181 NaN
2 -0.662690 1.534833 -0.859691 NaN
3 -2.452949 1.237274 -0.133712 NaN
4 1.414490 1.951676 -2.320422 NaN
5 -0.494922 -1.649727 -1.084601 NaN
6 -1.047551 -0.748572 -0.805479 NaN
7 NaN NaN NaN NaN
8 NaN NaN NaN NaN
9 NaN NaN NaN NaN
When doing an operation between DataFrame and Series, the default behavior is
to align the Seriesindex on the DataFramecolumns, thus broadcasting
row-wise. For example:
In [101]: df1=pd.DataFrame({"a":[1,0,1],"b":[0,1,1]},dtype=bool)In [102]: df2=pd.DataFrame({"a":[0,1,1],"b":[1,1,0]},dtype=bool)In [103]: df1&df2Out[103]: a b0 False False1 False True2 True FalseIn [104]: df1|df2Out[104]: a b0 True True1 True True2 True TrueIn [105]: df1^df2Out[105]: a b0 True True1 True False2 False TrueIn [106]: -df1Out[106]: a b0 False True1 True False2 False False
6 0.379495 0.274028 1.512461 1.318720
7 0.623732 0.986137 0.695904 0.993865
8 0.397301 2.449092 2.237242 0.299269
9 13.009059 4.183951 3.820223 0.310274
In [109]:
np
.
asarray
(
df
)
Out[109]:
array([[ 0.2719, -0.425 , 0.567 , 0.2762],
[-1.0874, -0.6737, 0.1136, -1.4784],
[ 0.525 , 0.4047, 0.577 , -1.715 ],
[-1.0393, -0.3706, -1.1579, -1.3443],
[ 0.8449, 1.0758, -0.109 , 1.6436],
[-1.4694, 0.357 , -0.6746, -1.7769],
[-0.9689, -1.2945, 0.4137, 0.2767],
[-0.472 , -0.014 , -0.3625, -0.0062],
[-0.9231, 0.8957, 0.8052, -1.2064],
[ 2.5656, 1.4313, 1.3403, -1.1703]])
DataFrame is not intended to be a drop-in replacement for ndarray as its
indexing semantics and data model are quite different in places from an n-dimensional
array.
When multiple Series are passed to a ufunc, they are aligned before
performing the operation.
Like other parts of the library, pandas will automatically align labeled inputs
as part of a ufunc with multiple inputs. For example, using numpy.remainder()
on two Series with differently ordered labels will align before the operation.
In [112]: ser1=pd.Series([1,2,3],index=["a","b","c"])In [113]: ser2=pd.Series([1,3,5],index=["b","a","c"])In [114]: ser1Out[114]: a 1b 2c 3dtype: int64In [115]: ser2Out[115]: b 1a 3c 5dtype: int64In [116]: np.remainder(ser1,ser2)Out[116]: a 1b 0c 3dtype: int64
As usual, the union of the two indices is taken, and non-overlapping values are filled
with missing values.
In [117]: ser3=pd.Series([2,4,6],index=["b","c","d"])In [118]: ser3Out[118]: b 2c 4d 6dtype: int64In [119]: np.remainder(ser1,ser3)Out[119]: a NaNb 0.0c 3.0d NaNdtype: float64
When a binary ufunc is applied to a Series and Index, the Series
implementation takes precedence and a Series is returned.
NumPy ufuncs are safe to apply to Series backed by non-ndarray arrays,
for example arrays.SparseArray (see Sparse calculation). If possible,
the ufunc is applied without converting the underlying data to an ndarray.
However, using DataFrame.to_string() will return a string representation of the
DataFrame in tabular form, though it won’t always fit the console width: