Intro to Data Structures¶
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, and axis labeling / alignment apply across all of the objects. To get started, import numpy and load pandas into your namespace:
In [225]: import numpy as np
# will use a lot in examples
In [226]: randn = np.random.randn
In [227]: from pandas import *
Here is a basic tenet to keep in mind: data alignment is intrinsic. 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 (technically a subclass of ndarray) 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 = 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 [228]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])
In [229]: s
Out[229]:
a -0.284
b -1.537
c 0.163
d -0.648
e -1.703
In [230]: s.index
Out[230]: Index([a, b, c, d, e], dtype=object)
In [231]: Series(randn(5))
Out[231]:
0 0.654
1 -1.146
2 1.144
3 0.167
4 0.148
Note
The values in the index must be unique. If they are not, an exception will not be raised immediately, but attempting any operation involving the index will later result in an exception. In other words, the Index object containing the labels “lazily” checks whether the values are unique. The reason for being lazy is nearly all performance-based (there are many instances in computations, like parts of GroupBy, where the index is not used).
From dict
If data is a dict, if index is passed the values in data corresponding to the labels in the index will be pulled out. Otherwise, an index will be constructed from the sorted keys of the dict, if possible.
In [232]: d = {'a' : 0., 'b' : 1., 'c' : 2.}
In [233]: Series(d)
Out[233]:
a 0
b 1
c 2
In [234]: Series(d, index=['b', 'c', 'd', 'a'])
Out[234]:
b 1
c 2
d NaN
a 0
Note
NaN (not a number) is the standard missing data marker used in pandas
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 [235]: Series(5., index=['a', 'b', 'c', 'd', 'e'])
Out[235]:
a 5
b 5
c 5
d 5
e 5
Series is ndarray-like¶
As a subclass of ndarray, Series is a valid argument to most NumPy functions and behaves similarly to a NumPy array. However, things like slicing also slice the index.
In [236]: s[0]
Out[236]: -0.28367872471747613
In [237]: s[:3]
Out[237]:
a -0.284
b -1.537
c 0.163
In [238]: s[s > s.median()]
Out[238]:
a -0.284
c 0.163
In [239]: s[[4, 3, 1]]
Out[239]:
e -1.703
d -0.648
b -1.537
In [240]: np.exp(s)
Out[240]:
a 0.753
b 0.215
c 1.177
d 0.523
e 0.182
We will address array-based indexing in a separate section.
Series is dict-like¶
A Series is alike a fixed-size dict in that you can get and set values by index label:
In [241]: s['a']
Out[241]: -0.28367872471747613
In [242]: s['e'] = 12.
In [243]: s
Out[243]:
a -0.284
b -1.537
c 0.163
d -0.648
e 12.000
In [244]: 'e' in s
Out[244]: True
In [245]: 'f' in s
Out[245]: False
If a label is not contained, an exception
>>> s['f']
KeyError: 'f'
>>> s.get('f')
nan
Vectorized operations and label alignment with Series¶
When doing data analysis, as with raw NumPy arrays looping through Series value-by-value is usually not necessary. Series can be also be passed into most NumPy methods expecting an ndarray.
In [246]: s + s
Out[246]:
a -0.567
b -3.074
c 0.326
d -1.296
e 24.000
In [247]: s * 2
Out[247]:
a -0.567
b -3.074
c 0.326
d -1.296
e 24.000
In [248]: np.exp(s)
Out[248]:
a 0.753
b 0.215
c 1.177
d 0.523
e 162754.791
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 [249]: s[1:] + s[:-1]
Out[249]:
a NaN
b -3.074
c 0.326
d -1.296
e NaN
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.
Note
In general, we chose to make the default result of operations between differently indexed objects yield the union of the indexes in order to avoid loss of information. Having an index label, though the data is missing, is typically important information as part of a computation. You of course have the option of dropping labels with missing data via the dropna function.
Name attribute¶
Series can also have a name attribute:
In [250]: s = Series(np.random.randn(5), name='something')
In [251]: s
Out[251]:
0 -1.334
1 -0.171
2 0.050
3 -0.650
4 -1.084
Name: something
In [252]: s.name
Out[252]: 'something'
The Series name will be assigned automatically in many cases, in particular when taking 1D slices of DataFrame as you will see below.
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:
- Dict of 1D ndarrays, lists, dicts, or Series
- 2-D numpy.ndarray
- Structured or record ndarray
- A Series
- Another DataFrame
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 result index will be the union of the indexes of the various Series. If there are any nested dicts, these will be first converted to Series. If no columns are passed, the columns will be the sorted list of dict keys.
In [253]: d = {'one' : Series([1., 2., 3.], index=['a', 'b', 'c']),
.....: 'two' : Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
In [254]: df = DataFrame(d)
In [255]: df
Out[255]:
one two
a 1 1
b 2 2
c 3 3
d NaN 4
In [256]: DataFrame(d, index=['d', 'b', 'a'])
Out[256]:
one two
d NaN 4
b 2 2
a 1 1
In [257]: DataFrame(d, index=['d', 'b', 'a'], columns=['two', 'three'])
Out[257]:
two three
d 4 NaN
b 2 NaN
a 1 NaN
The row and column labels can be accessed respectively by accessing the index and columns attributes:
Note
When a particular set of columns is passed along with a dict of data, the passed columns override the keys in the dict.
In [258]: df.index
Out[258]: Index([a, b, c, d], dtype=object)
In [259]: df.columns
Out[259]: Index([one, two], dtype=object)
From dict of ndarrays / lists¶
The ndarrays must all be the same length. If an index is passed, it must clearly 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 [260]: d = {'one' : [1., 2., 3., 4.],
.....: 'two' : [4., 3., 2., 1.]}
In [261]: DataFrame(d)
Out[261]:
one two
0 1 4
1 2 3
2 3 2
3 4 1
In [262]: DataFrame(d, index=['a', 'b', 'c', 'd'])
Out[262]:
one two
a 1 4
b 2 3
c 3 2
d 4 1
From structured or record array¶
This case is handled identically to a dict of arrays.
In [263]: data = np.zeros((2,),dtype=[('A', 'i4'),('B', 'f4'),('C', 'a10')])
In [264]: data[:] = [(1,2.,'Hello'),(2,3.,"World")]
In [265]: DataFrame(data)
Out[265]:
A B C
0 1 2 Hello
1 2 3 World
In [266]: DataFrame(data, index=['first', 'second'])
Out[266]:
A B C
first 1 2 Hello
second 2 3 World
In [267]: DataFrame(data, columns=['C', 'A', 'B'])
Out[267]:
C A B
0 Hello 1 2
1 World 2 3
Note
DataFrame is not intended to work exactly like a 2-dimensional NumPy ndarray.
From a list of dicts¶
In [268]: data2 = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}]
In [269]: DataFrame(data2)
Out[269]:
a b c
0 1 2 NaN
1 5 10 20
In [270]: DataFrame(data2, index=['first', 'second'])
Out[270]:
a b c
first 1 2 NaN
second 5 10 20
In [271]: DataFrame(data2, columns=['a', 'b'])
Out[271]:
a b
0 1 2
1 5 10
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).
Missing Data
Much more will be said on this topic in the Missing data section. To construct a DataFrame with missing data, use np.nan for those values which are missing. Alternatively, you may pass a numpy.MaskedArray as the data argument to the DataFrame constructor, and its masked entries will be considered missing.
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.
DataFrame.from_records
DataFrame.from_records takes a list of tuples or an ndarray with structured dtype. Works analogously to the normal DataFrame constructor, except that index maybe be a specific field of the structured dtype to use as the index. For example:
In [272]: data
Out[272]:
array([(1, 2.0, 'Hello'), (2, 3.0, 'World')],
dtype=[('A', '<i4'), ('B', '<f4'), ('C', '|S10')])
In [273]: DataFrame.from_records(data, index='C')
Out[273]:
A B
Hello 1 2
World 2 3
DataFrame.from_items
DataFrame.from_items works analogously to the form of the dict constructor that takes a sequence of (key, value) pairs, where the keys are column (or row, in the case of orient='index') names, and the value are the column values (or row values). This can be useful for constructing a DataFrame with the columns in a particular order without having to pass an explicit list of columns:
In [274]: DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])])
Out[274]:
A B
0 1 4
1 2 5
2 3 6
If you pass orient='index', the keys will be the row labels. But in this case you must also pass the desired column names:
In [275]: DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])],
.....: orient='index', columns=['one', 'two', 'three'])
Out[275]:
one two three
A 1 2 3
B 4 5 6
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 [276]: df['one']
Out[276]:
a 1
b 2
c 3
d NaN
Name: one
In [277]: df['three'] = df['one'] * df['two']
In [278]: df['flag'] = df['one'] > 2
In [279]: df
Out[279]:
one two three flag
a 1 1 1 False
b 2 2 4 False
c 3 3 9 True
d NaN 4 NaN False
Columns can be deleted or popped like with a dict:
In [280]: del df['two']
In [281]: three = df.pop('three')
In [282]: df
Out[282]:
one flag
a 1 False
b 2 False
c 3 True
d NaN False
When inserting a scalar value, it will naturally be propagated to fill the column:
In [283]: df['foo'] = 'bar'
In [284]: df
Out[284]:
one flag foo
a 1 False bar
b 2 False bar
c 3 True bar
d 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 [285]: df['one_trunc'] = df['one'][:2]
In [286]: df
Out[286]:
one flag foo one_trunc
a 1 False bar 1
b 2 False bar 2
c 3 True bar NaN
d 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. The insert function is available to insert at a particular location in the columns:
In [287]: df.insert(1, 'bar', df['one'])
In [288]: df
Out[288]:
one bar flag foo one_trunc
a 1 1 False bar 1
b 2 2 False bar 2
c 3 3 True bar NaN
d NaN NaN False bar NaN
Indexing / Selection¶
The basics of indexing are as follows:
Operation | Syntax | Result |
---|---|---|
Select column | df[col] | Series |
Select row by label | df.xs(label) or df.ix[label] | Series |
Select row by location (int) | df.ix[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 [289]: df.xs('b')
Out[289]:
one 2
bar 2
flag False
foo bar
one_trunc 2
Name: b
In [290]: df.ix[2]
Out[290]:
one 3
bar 3
flag True
foo bar
one_trunc NaN
Name: c
Note if a DataFrame contains columns of multiple dtypes, the dtype of the row will be chosen to accommodate all of the data types (dtype=object is the most general).
For a more exhaustive treatment of more sophisticated label-based indexing and slicing, see the section on indexing. We will address the fundamentals of reindexing / conforming to new sets of lables in the section on reindexing.
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 [291]: df = DataFrame(randn(10, 4), columns=['A', 'B', 'C', 'D'])
In [292]: df2 = DataFrame(randn(7, 3), columns=['A', 'B', 'C'])
In [293]: df + df2
Out[293]:
A B C D
0 0.002 0.831 -1.171 NaN
1 0.269 3.238 0.268 NaN
2 -0.513 0.090 3.120 NaN
3 0.684 1.042 2.282 NaN
4 1.188 -1.805 1.166 NaN
5 -1.972 0.407 -3.513 NaN
6 -0.850 0.306 0.237 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 Series index on the DataFrame columns, thus broadcasting row-wise. For example:
In [294]: df - df.ix[0]
Out[294]:
A B C D
0 0.000 0.000 0.000 0.000
1 0.808 1.358 2.420 -1.339
2 -0.070 -0.814 4.027 -0.293
3 0.073 -0.519 2.195 -0.002
4 1.342 0.372 2.510 -1.543
5 -0.523 0.665 0.942 0.018
6 0.101 -0.066 1.943 -0.817
7 0.744 0.834 3.473 -0.665
8 0.045 0.772 1.406 -0.965
9 0.860 1.677 1.462 -1.165
In the special case of working with time series data, if the Series is a TimeSeries (which it will be automatically if the index contains datetime objects), and the DataFrame index also contains dates, the broadcasting will be column-wise:
In [295]: index = DateRange('1/1/2000', periods=8)
In [296]: df = DataFrame(randn(8, 3), index=index,
.....: columns=['A', 'B', 'C'])
In [297]: df
Out[297]:
A B C
2000-01-03 0.361 -0.192 -0.058
2000-01-04 -0.646 -1.051 -0.716
2000-01-05 0.613 0.501 -1.380
2000-01-06 0.624 0.790 0.818
2000-01-07 1.559 0.335 0.919
2000-01-10 -1.381 0.365 -1.811
2000-01-11 -0.673 -1.968 -0.401
2000-01-12 -0.583 -0.999 -0.629
In [298]: type(df['A'])
Out[298]: pandas.core.series.TimeSeries
In [299]: df - df['A']
Out[299]:
A B C
2000-01-03 0 -0.553 -0.419
2000-01-04 0 -0.405 -0.070
2000-01-05 0 -0.112 -1.993
2000-01-06 0 0.166 0.195
2000-01-07 0 -1.224 -0.640
2000-01-10 0 1.746 -0.429
2000-01-11 0 -1.294 0.272
2000-01-12 0 -0.416 -0.046
Technical purity aside, this case is so common in practice that supporting the special case is preferable to the alternative of forcing the user to transpose and do column-based alignment like so:
In [300]: (df.T - df['A']).T
Out[300]:
A B C
2000-01-03 0 -0.553 -0.419
2000-01-04 0 -0.405 -0.070
2000-01-05 0 -0.112 -1.993
2000-01-06 0 0.166 0.195
2000-01-07 0 -1.224 -0.640
2000-01-10 0 1.746 -0.429
2000-01-11 0 -1.294 0.272
2000-01-12 0 -0.416 -0.046
For explicit control over the matching and broadcasting behavior, see the section on flexible binary operations.
Operations with scalars are just as you would expect:
In [301]: df * 5 + 2
Out[301]:
A B C
2000-01-03 3.805 1.040 1.708
2000-01-04 -1.230 -3.257 -1.580
2000-01-05 5.064 4.504 -4.902
2000-01-06 5.118 5.948 6.091
2000-01-07 9.795 3.676 6.597
2000-01-10 -4.906 3.826 -7.053
2000-01-11 -1.367 -7.838 -0.006
2000-01-12 -0.915 -2.993 -1.146
In [302]: 1 / df
Out[302]:
A B C
2000-01-03 2.770 -5.211 -17.148
2000-01-04 -1.548 -0.951 -1.397
2000-01-05 1.632 1.997 -0.724
2000-01-06 1.604 1.266 1.222
2000-01-07 0.641 2.983 1.088
2000-01-10 -0.724 2.738 -0.552
2000-01-11 -1.485 -0.508 -2.493
2000-01-12 -1.715 -1.001 -1.589
In [303]: df ** 4
Out[303]:
A B C
2000-01-03 0.017 0.001 0.000
2000-01-04 0.174 1.222 0.263
2000-01-05 0.141 0.063 3.631
2000-01-06 0.151 0.389 0.448
2000-01-07 5.908 0.013 0.715
2000-01-10 3.639 0.018 10.748
2000-01-11 0.206 14.988 0.026
2000-01-12 0.116 0.995 0.157
Boolean operators work as well:
In [304]: df1 = DataFrame({'a' : [1, 0, 1], 'b' : [0, 1, 1] }, dtype=bool)
In [305]: df2 = DataFrame({'a' : [0, 1, 1], 'b' : [1, 1, 0] }, dtype=bool)
In [306]: df1 & df2
Out[306]:
a b
0 False False
1 False True
2 True False
In [307]: df1 | df2
Out[307]:
a b
0 True True
1 True True
2 True True
In [308]: df1 ^ df2
Out[308]:
a b
0 True True
1 True False
2 False True
In [309]: -df1
Out[309]:
a b
0 False True
1 True False
2 False False
Transposing¶
To transpose, access the T attribute (also the transpose function), similar to an ndarray:
# only show the first 5 rows
In [310]: df[:5].T
Out[310]:
2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07
A 0.361 -0.646 0.613 0.624 1.559
B -0.192 -1.051 0.501 0.790 0.335
C -0.058 -0.716 -1.380 0.818 0.919
DataFrame interoperability with NumPy functions¶
Elementwise NumPy ufuncs (log, exp, sqrt, ...) and various other NumPy functions can be used with no issues on DataFrame, assuming the data within are numeric:
In [311]: np.exp(df)
Out[311]:
A B C
2000-01-03 1.435 0.825 0.943
2000-01-04 0.524 0.349 0.489
2000-01-05 1.846 1.650 0.251
2000-01-06 1.866 2.203 2.267
2000-01-07 4.754 1.398 2.508
2000-01-10 0.251 1.441 0.164
2000-01-11 0.510 0.140 0.670
2000-01-12 0.558 0.368 0.533
In [312]: np.asarray(df)
Out[312]:
array([[ 0.361 , -0.1919, -0.0583],
[-0.646 , -1.0514, -0.716 ],
[ 0.6128, 0.5007, -1.3804],
[ 0.6236, 0.7896, 0.8183],
[ 1.5591, 0.3352, 0.9194],
[-1.3812, 0.3652, -1.8106],
[-0.6734, -1.9676, -0.4012],
[-0.583 , -0.9986, -0.6293]])
The dot method on DataFrame implements matrix multiplication:
In [313]: df.T.dot(df)
Out[313]:
A B C
A 6.444 3.334 4.677
B 3.334 7.131 1.784
C 4.677 1.784 7.772
Similarly, the dot method on Series implements dot product:
In [314]: s1 = Series(np.arange(5,10))
In [315]: s1.dot(s1)
Out[315]: 255
DataFrame is not intended to be a drop-in replacement for ndarray as its indexing semantics are quite different in places from a matrix.
Console display¶
For very large DataFrame objects, only a summary will be printed to the console (here I am reading a CSV version of the baseball dataset from the plyr R package):
In [316]: baseball = read_csv('data/baseball.csv')
In [317]: print baseball
<class 'pandas.core.frame.DataFrame'>
Int64Index: 100 entries, 88641 to 89534
Data columns:
id 100 non-null values
year 100 non-null values
stint 100 non-null values
team 100 non-null values
lg 100 non-null values
g 100 non-null values
ab 100 non-null values
r 100 non-null values
h 100 non-null values
X2b 100 non-null values
X3b 100 non-null values
hr 100 non-null values
rbi 100 non-null values
sb 100 non-null values
cs 100 non-null values
bb 100 non-null values
so 100 non-null values
ibb 100 non-null values
hbp 100 non-null values
sh 100 non-null values
sf 100 non-null values
gidp 100 non-null values
dtypes: float64(9), int64(10), object(3)
However, using to_string will return a string representation of the DataFrame in tabular form, though it won’t always fit the console width:
In [318]: print baseball.ix[-20:, :12].to_string()
id year stint team lg g ab r h X2b X3b hr
88641 womacto01 2006 2 CHN NL 19 50 6 14 1 0 1
88643 schilcu01 2006 1 BOS AL 31 2 0 1 0 0 0
88645 myersmi01 2006 1 NYA AL 62 0 0 0 0 0 0
88649 helliri01 2006 1 MIL NL 20 3 0 0 0 0 0
88650 johnsra05 2006 1 NYA AL 33 6 0 1 0 0 0
88652 finlest01 2006 1 SFN NL 139 426 66 105 21 12 6
88653 gonzalu01 2006 1 ARI NL 153 586 93 159 52 2 15
88662 seleaa01 2006 1 LAN NL 28 26 2 5 1 0 0
89177 francju01 2007 2 ATL NL 15 40 1 10 3 0 0
89178 francju01 2007 1 NYN NL 40 50 7 10 0 0 1
89330 zaungr01 2007 1 TOR AL 110 331 43 80 24 1 10
89333 witasja01 2007 1 TBA AL 3 0 0 0 0 0 0
89334 williwo02 2007 1 HOU NL 33 59 3 6 0 0 1
89335 wickmbo01 2007 2 ARI NL 8 0 0 0 0 0 0
89336 wickmbo01 2007 1 ATL NL 47 0 0 0 0 0 0
89337 whitero02 2007 1 MIN AL 38 109 8 19 4 0 4
89338 whiteri01 2007 1 HOU NL 20 1 0 0 0 0 0
89339 wellsda01 2007 2 LAN NL 7 15 2 4 1 0 0
89340 wellsda01 2007 1 SDN NL 22 38 1 4 0 0 0
89341 weathda01 2007 1 CIN NL 67 0 0 0 0 0 0
89343 walketo04 2007 1 OAK AL 18 48 5 13 1 0 0
89345 wakefti01 2007 1 BOS AL 1 2 0 0 0 0 0
89347 vizquom01 2007 1 SFN NL 145 513 54 126 18 3 4
89348 villoro01 2007 1 NYA AL 6 0 0 0 0 0 0
89352 valenjo03 2007 1 NYN NL 51 166 18 40 11 1 3
89354 trachst01 2007 2 CHN NL 4 7 0 1 0 0 0
89355 trachst01 2007 1 BAL AL 3 5 0 0 0 0 0
89359 timlimi01 2007 1 BOS AL 4 0 0 0 0 0 0
89360 thomeji01 2007 1 CHA AL 130 432 79 119 19 0 35
89361 thomafr04 2007 1 TOR AL 155 531 63 147 30 0 26
89363 tavarju01 2007 1 BOS AL 2 4 0 1 0 0 0
89365 sweenma01 2007 2 LAN NL 30 33 2 9 1 0 0
89366 sweenma01 2007 1 SFN NL 76 90 18 23 8 0 2
89367 suppaje01 2007 1 MIL NL 33 61 4 8 0 0 0
89368 stinnke01 2007 1 SLN NL 26 82 7 13 3 0 1
89370 stantmi02 2007 1 CIN NL 67 2 0 0 0 0 0
89371 stairma01 2007 1 TOR AL 125 357 58 103 28 1 21
89372 sprinru01 2007 1 SLN NL 72 1 0 0 0 0 0
89374 sosasa01 2007 1 TEX AL 114 412 53 104 24 1 21
89375 smoltjo01 2007 1 ATL NL 30 54 1 5 1 0 0
89378 sheffga01 2007 1 DET AL 133 494 107 131 20 1 25
89381 seleaa01 2007 1 NYN NL 31 4 0 0 0 0 0
89382 seaneru01 2007 1 LAN NL 68 1 0 0 0 0 0
89383 schmija01 2007 1 LAN NL 6 7 1 1 0 0 1
89384 schilcu01 2007 1 BOS AL 1 2 0 1 0 0 0
89385 sandere02 2007 1 KCA AL 24 73 12 23 7 0 2
89388 rogerke01 2007 1 DET AL 1 2 0 0 0 0 0
89389 rodriiv01 2007 1 DET AL 129 502 50 141 31 3 11
89396 ramirma02 2007 1 BOS AL 133 483 84 143 33 1 20
89398 piazzmi01 2007 1 OAK AL 83 309 33 85 17 1 8
89400 perezne01 2007 1 DET AL 33 64 5 11 3 0 1
89402 parkch01 2007 1 NYN NL 1 1 0 0 0 0 0
89406 oliveda02 2007 1 LAA AL 5 0 0 0 0 0 0
89410 myersmi01 2007 1 NYA AL 6 1 0 0 0 0 0
89411 mussimi01 2007 1 NYA AL 2 2 0 0 0 0 0
89412 moyerja01 2007 1 PHI NL 33 73 4 9 2 0 0
89420 mesajo01 2007 1 PHI NL 38 0 0 0 0 0 0
89421 martipe02 2007 1 NYN NL 5 9 1 1 1 0 0
89425 maddugr01 2007 1 SDN NL 33 62 2 9 2 0 0
89426 mabryjo01 2007 1 COL NL 28 34 4 4 1 0 1
89429 loftoke01 2007 2 CLE AL 52 173 24 49 9 3 0
89430 loftoke01 2007 1 TEX AL 84 317 62 96 16 3 7
89431 loaizes01 2007 1 LAN NL 5 7 0 1 0 0 0
89438 kleskry01 2007 1 SFN NL 116 362 51 94 27 3 6
89439 kentje01 2007 1 LAN NL 136 494 78 149 36 1 20
89442 jonesto02 2007 1 DET AL 5 0 0 0 0 0 0
89445 johnsra05 2007 1 ARI NL 10 15 0 1 0 0 0
89450 hoffmtr01 2007 1 SDN NL 60 0 0 0 0 0 0
89451 hernaro01 2007 2 LAN NL 22 0 0 0 0 0 0
89452 hernaro01 2007 1 CLE AL 2 0 0 0 0 0 0
89460 guarded01 2007 1 CIN NL 15 0 0 0 0 0 0
89462 griffke02 2007 1 CIN NL 144 528 78 146 24 1 30
89463 greensh01 2007 1 NYN NL 130 446 62 130 30 1 10
89464 graffto01 2007 1 MIL NL 86 231 34 55 8 0 9
89465 gordoto01 2007 1 PHI NL 44 0 0 0 0 0 0
89466 gonzalu01 2007 1 LAN NL 139 464 70 129 23 2 15
89467 gomezch02 2007 2 CLE AL 19 53 4 15 2 0 0
89468 gomezch02 2007 1 BAL AL 73 169 17 51 10 1 1
89469 glavito02 2007 1 NYN NL 33 56 3 12 1 0 0
89473 floydcl01 2007 1 CHN NL 108 282 40 80 10 1 9
89474 finlest01 2007 1 COL NL 43 94 9 17 3 0 1
89480 embreal01 2007 1 OAK AL 4 0 0 0 0 0 0
89481 edmonji01 2007 1 SLN NL 117 365 39 92 15 2 12
89482 easleda01 2007 1 NYN NL 76 193 24 54 6 0 10
89489 delgaca01 2007 1 NYN NL 139 538 71 139 30 0 24
89493 cormirh01 2007 1 CIN NL 6 0 0 0 0 0 0
89494 coninje01 2007 2 NYN NL 21 41 2 8 2 0 0
89495 coninje01 2007 1 CIN NL 80 215 23 57 11 1 6
89497 clemero02 2007 1 NYA AL 2 2 0 1 0 0 0
89498 claytro01 2007 2 BOS AL 8 6 1 0 0 0 0
89499 claytro01 2007 1 TOR AL 69 189 23 48 14 0 1
89501 cirilje01 2007 2 ARI NL 28 40 6 8 4 0 0
89502 cirilje01 2007 1 MIN AL 50 153 18 40 9 2 2
89521 bondsba01 2007 1 SFN NL 126 340 75 94 14 0 28
89523 biggicr01 2007 1 HOU NL 141 517 68 130 31 3 10
89525 benitar01 2007 2 FLO NL 34 0 0 0 0 0 0
89526 benitar01 2007 1 SFN NL 19 0 0 0 0 0 0
89530 ausmubr01 2007 1 HOU NL 117 349 38 82 16 3 3
89533 aloumo01 2007 1 NYN NL 87 328 51 112 19 1 13
89534 alomasa02 2007 1 NYN NL 8 22 1 3 1 0 0
DataFrame column types¶
The four main types stored in pandas objects are float, int, boolean, and object. A convenient dtypes attribute return a Series with the data type of each column:
In [319]: baseball.dtypes
Out[319]:
id object
year int64
stint int64
team object
lg object
g int64
ab int64
r int64
h int64
X2b int64
X3b int64
hr int64
rbi float64
sb float64
cs float64
bb int64
so float64
ibb float64
hbp float64
sh float64
sf float64
gidp float64
The related method get_dtype_counts will return the number of columns of each type:
In [320]: baseball.get_dtype_counts()
Out[320]:
float64 9
int64 10
object 3
DataFrame column attribute access and IPython completion¶
If a DataFrame column label is a valid Python variable name, the column can be accessed like attributes:
In [321]: df = DataFrame({'foo1' : np.random.randn(5),
.....: 'foo2' : np.random.randn(5)})
In [322]: df
Out[322]:
foo1 foo2
0 -0.548001 -0.966162
1 -0.852612 -0.332601
2 -0.126250 -1.327330
3 1.765997 1.225847
4 -1.593297 -0.348395
In [323]: df.foo1
Out[323]:
0 -0.548001
1 -0.852612
2 -0.126250
3 1.765997
4 -1.593297
Name: foo1
The columns are also connected to the IPython completion mechanism so they can be tab-completed:
In [5]: df.fo<TAB>
df.foo1 df.foo2
Panel¶
Panel is a somewhat less-used, but still important container for 3-dimensional data. The term panel data is derived from econometrics and is partially responsible for the name pandas: pan(el)-da(ta)-s. The names for the 3 axes are intended to give some semantic meaning to describing operations involving panel data and, in particular, econometric analysis of panel data. However, for the strict purposes of slicing and dicing a collection of DataFrame objects, you may find the axis names slightly arbitrary:
- items: axis 0, each item corresponds to a DataFrame contained inside
- major_axis: axis 1, it is the index (rows) of each of the DataFrames
- minor_axis: axis 2, it is the columns of each of the DataFrames
Construction of Panels works about like you would expect:
From 3D ndarray with optional axis labels¶
In [324]: wp = Panel(randn(2, 5, 4), items=['Item1', 'Item2'],
.....: major_axis=DateRange('1/1/2000', periods=5),
.....: minor_axis=['A', 'B', 'C', 'D'])
In [325]: wp
Out[325]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 5 (major) x 4 (minor)
Items: Item1 to Item2
Major axis: 2000-01-03 00:00:00 to 2000-01-07 00:00:00
Minor axis: A to D
From dict of DataFrame objects¶
In [326]: data = {'Item1' : DataFrame(randn(4, 3)),
.....: 'Item2' : DataFrame(randn(4, 2))}
In [327]: Panel(data)
Out[327]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 4 (major) x 3 (minor)
Items: Item1 to Item2
Major axis: 0 to 3
Minor axis: 0 to 2
Note that the values in the dict need only be convertible to DataFrame. Thus, they can be any of the other valid inputs to DataFrame as per above.
One helpful factory method is Panel.from_dict, which takes a dictionary of DataFrames as above, and the following named parameters:
Parameter | Default | Description |
---|---|---|
intersect | False | drops elements whose indices do not align |
orient | items | use minor to use DataFrames’ columns as panel items |
For example, compare to the construction above:
In [328]: Panel.from_dict(data, orient='minor')
Out[328]:
<class 'pandas.core.panel.Panel'>
Dimensions: 3 (items) x 4 (major) x 2 (minor)
Items: 0 to 2
Major axis: 0 to 3
Minor axis: Item1 to Item2
Orient is especially useful for mixed-type DataFrames. If you pass a dict of DataFrame objects with mixed-type columns, all of the data will get upcasted to dtype=object unless you pass orient='minor':
In [329]: df = DataFrame({'a': ['foo', 'bar', 'baz'],
.....: 'b': np.random.randn(3)})
In [330]: df
Out[330]:
a b
0 foo -1.309989
1 bar -1.153000
2 baz 0.606382
In [331]: data = {'item1': df, 'item2': df}
In [332]: panel = Panel.from_dict(data, orient='minor')
In [333]: panel['a']
Out[333]:
item1 item2
0 foo foo
1 bar bar
2 baz baz
In [334]: panel['b']
Out[334]:
item1 item2
0 -1.309989 -1.309989
1 -1.153000 -1.153000
2 0.606382 0.606382
In [335]: panel['b'].dtypes
Out[335]:
item1 float64
item2 float64
Note
Unfortunately Panel, being less commonly used than Series and DataFrame, has been slightly neglected feature-wise. A number of methods and options available in DataFrame are not available in Panel. This will get worked on, of course, in future releases. And faster if you join me in working on the codebase.
From DataFrame using to_panel method¶
This method was introduced in v0.7 to replace LongPanel.to_long, and converts a DataFrame with a two-level index to a Panel.
In [336]: midx = MultiIndex(levels=[['one', 'two'], ['x','y']], labels=[[1,1,0,0],[1,0,1,0]])
In [337]: df = DataFrame({'A' : [1, 2, 3, 4], 'B': [5, 6, 7, 8]}, index=midx)
In [338]: df.to_panel()
Out[338]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major) x 2 (minor)
Items: A to B
Major axis: one to two
Minor axis: x to y
Item selection / addition / deletion¶
Similar to DataFrame functioning as a dict of Series, Panel is like a dict of DataFrames:
In [339]: wp['Item1']
Out[339]:
A B C D
2000-01-03 1.424840 -0.879202 0.544803 0.627214
2000-01-04 0.696649 0.107734 -0.776466 -1.257592
2000-01-05 -0.600682 -1.504853 1.052050 0.586573
2000-01-06 -2.637236 -0.014948 -1.208531 -1.257020
2000-01-07 -0.499747 0.429787 -0.242210 -0.723848
In [340]: wp['Item3'] = wp['Item1'] / wp['Item2']
The API for insertion and deletion is the same as for DataFrame. And as with DataFrame, if the item is a valid python identifier, you can access it as an attribute and tab-complete it in IPython.
Indexing / Selection¶
Operation | Syntax | Result |
---|---|---|
Select item | wp[item] | DataFrame |
Get slice at major_axis label | wp.major_xs(val) | DataFrame |
Get slice at minor_axis label | wp.minor_xs(val) | DataFrame |
For example, using the earlier example data, we could do:
In [341]: wp['Item1']
Out[341]:
A B C D
2000-01-03 1.424840 -0.879202 0.544803 0.627214
2000-01-04 0.696649 0.107734 -0.776466 -1.257592
2000-01-05 -0.600682 -1.504853 1.052050 0.586573
2000-01-06 -2.637236 -0.014948 -1.208531 -1.257020
2000-01-07 -0.499747 0.429787 -0.242210 -0.723848
In [342]: wp.major_xs(wp.major_axis[2])
Out[342]:
Item1 Item2 Item3
A -0.600682 -2.138612 0.280875
B -1.504853 -0.592654 2.539177
C 1.052050 -1.059136 -0.993309
D 0.586573 0.118816 4.936815
In [343]: wp.minor_axis
Out[343]: Index([A, B, C, D], dtype=object)
In [344]: wp.minor_xs('C')
Out[344]:
Item1 Item2 Item3
2000-01-03 0.544803 -0.543730 -1.001973
2000-01-04 -0.776466 -1.566259 0.495746
2000-01-05 1.052050 -1.059136 -0.993309
2000-01-06 -1.208531 -0.129101 9.361112
2000-01-07 -0.242210 0.759091 -0.319079
Conversion to DataFrame¶
A Panel can be represented in 2D form as a hierarchically indexed DataFrame. See the section hierarchical indexing for more on this. To convert a Panel to a DataFrame, use the to_frame method:
In [345]: panel = Panel(np.random.randn(3, 5, 4), items=['one', 'two', 'three'],
.....: major_axis=DateRange('1/1/2000', periods=5),
.....: minor_axis=['a', 'b', 'c', 'd'])
In [346]: panel.to_frame()
Out[346]:
one two three
major minor
2000-01-03 a -0.681101 -0.254002 -0.139981
b -0.289724 1.360151 -0.040368
c -0.996632 -0.059912 -1.742251
d -1.407699 -0.151652 0.234716
2000-01-04 a 1.014104 0.624697 0.876834
b 0.314226 -1.124779 0.080597
c -0.001675 0.072594 -0.000185
d 0.071823 -1.109831 -0.264704
2000-01-05 a 0.892566 -0.008027 -0.566820
b 0.680594 -0.121632 -1.643966
c -0.339640 0.045829 1.471262
d 0.214910 0.532980 0.677634
2000-01-06 a -0.078410 0.228178 -0.485743
b -0.177665 -0.210935 -0.342272
c 0.490838 0.039513 -1.042291
d -1.360102 -0.205689 -0.611457
2000-01-07 a 1.592456 -0.764740 -0.141224
b 1.007100 0.027476 0.007220
c 0.697835 -0.277396 -0.516147
d -1.890591 0.620539 0.446161