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 [224]: import numpy as np
# will use a lot in examples
In [225]: randn = np.random.randn
In [226]: 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 [227]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])
In [228]: s
Out[228]:
a -0.284
b -1.537
c 0.163
d -0.648
e -1.703
In [229]: s.index
Out[229]: Index([a, b, c, d, e], dtype=object)
In [230]: Series(randn(5))
Out[230]:
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 [231]: d = {'a' : 0., 'b' : 1., 'c' : 2.}
In [232]: Series(d)
Out[232]:
a 0
b 1
c 2
In [233]: Series(d, index=['b', 'c', 'd', 'a'])
Out[233]:
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 [234]: Series(5., index=['a', 'b', 'c', 'd', 'e'])
Out[234]:
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 [235]: s[0]
Out[235]: -0.28367872471747613
In [236]: s[:3]
Out[236]:
a -0.284
b -1.537
c 0.163
In [237]: s[s > s.median()]
Out[237]:
a -0.284
c 0.163
In [238]: s[[4, 3, 1]]
Out[238]:
e -1.703
d -0.648
b -1.537
In [239]: np.exp(s)
Out[239]:
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 [240]: s['a']
Out[240]: -0.28367872471747613
In [241]: s['e'] = 12.
In [242]: s
Out[242]:
a -0.284
b -1.537
c 0.163
d -0.648
e 12.000
In [243]: 'e' in s
Out[243]: True
In [244]: 'f' in s
Out[244]: 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 [245]: s + s
Out[245]:
a -0.567
b -3.074
c 0.326
d -1.296
e 24.000
In [246]: s * 2
Out[246]:
a -0.567
b -3.074
c 0.326
d -1.296
e 24.000
In [247]: np.exp(s)
Out[247]:
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 [248]: s[1:] + s[:-1]
Out[248]:
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 [249]: s = Series(np.random.randn(5), name='something')
In [250]: s
Out[250]:
0 -1.334
1 -0.171
2 0.050
3 -0.650
4 -1.084
Name: something
In [251]: s.name
Out[251]: '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 [252]: d = {'one' : Series([1., 2., 3.], index=['a', 'b', 'c']),
.....: 'two' : Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
In [253]: df = DataFrame(d)
In [254]: df
Out[254]:
one two
a 1 1
b 2 2
c 3 3
d NaN 4
In [255]: DataFrame(d, index=['d', 'b', 'a'])
Out[255]:
one two
d NaN 4
b 2 2
a 1 1
In [256]: DataFrame(d, index=['d', 'b', 'a'], columns=['two', 'three'])
Out[256]:
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 [257]: df.index
Out[257]: Index([a, b, c, d], dtype=object)
In [258]: df.columns
Out[258]: 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 [259]: d = {'one' : [1., 2., 3., 4.],
.....: 'two' : [4., 3., 2., 1.]}
In [260]: DataFrame(d)
Out[260]:
one two
0 1 4
1 2 3
2 3 2
3 4 1
In [261]: DataFrame(d, index=['a', 'b', 'c', 'd'])
Out[261]:
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 [262]: data = np.zeros((2,),dtype=[('A', 'i4'),('B', 'f4'),('C', 'a10')])
In [263]: data[:] = [(1,2.,'Hello'),(2,3.,"World")]
In [264]: DataFrame(data)
Out[264]:
A B C
0 1 2 Hello
1 2 3 World
In [265]: DataFrame(data, index=['first', 'second'])
Out[265]:
A B C
first 1 2 Hello
second 2 3 World
In [266]: DataFrame(data, columns=['C', 'A', 'B'])
Out[266]:
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 [267]: data2 = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}]
In [268]: DataFrame(data2)
Out[268]:
a b c
0 1 2 NaN
1 5 10 20
In [269]: DataFrame(data2, index=['first', 'second'])
Out[269]:
a b c
first 1 2 NaN
second 5 10 20
In [270]: DataFrame(data2, columns=['a', 'b'])
Out[270]:
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 [271]: data
Out[271]:
array([(1, 2.0, 'Hello'), (2, 3.0, 'World')],
dtype=[('A', '<i4'), ('B', '<f4'), ('C', '|S10')])
In [272]: DataFrame.from_records(data, index='C')
Out[272]:
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 [273]: DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])])
Out[273]:
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 [274]: DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])],
.....: orient='index', columns=['one', 'two', 'three'])
Out[274]:
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 [275]: df['one']
Out[275]:
a 1
b 2
c 3
d NaN
Name: one
In [276]: df['three'] = df['one'] * df['two']
In [277]: df['flag'] = df['one'] > 2
In [278]: df
Out[278]:
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 [279]: del df['two']
In [280]: three = df.pop('three')
In [281]: df
Out[281]:
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 [282]: df['foo'] = 'bar'
In [283]: df
Out[283]:
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 [284]: df['one_trunc'] = df['one'][:2]
In [285]: df
Out[285]:
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 [286]: df.insert(1, 'bar', df['one'])
In [287]: df
Out[287]:
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 [288]: df.xs('b')
Out[288]:
one 2
bar 2
flag False
foo bar
one_trunc 2
Name: b
In [289]: df.ix[2]
Out[289]:
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 [290]: df = DataFrame(randn(10, 4), columns=['A', 'B', 'C', 'D'])
In [291]: df2 = DataFrame(randn(7, 3), columns=['A', 'B', 'C'])
In [292]: df + df2
Out[292]:
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 [293]: df - df.ix[0]
Out[293]:
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 [294]: index = DateRange('1/1/2000', periods=8)
In [295]: df = DataFrame(randn(8, 3), index=index,
.....: columns=['A', 'B', 'C'])
In [296]: df
Out[296]:
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 [297]: type(df['A'])
Out[297]: pandas.core.series.TimeSeries
In [298]: df - df['A']
Out[298]:
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 [299]: (df.T - df['A']).T
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
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 [300]: df * 5 + 2
Out[300]:
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 [301]: 1 / df
Out[301]:
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 [302]: df ** 4
Out[302]:
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 [303]: df1 = DataFrame({'a' : [1, 0, 1], 'b' : [0, 1, 1] }, dtype=bool)
In [304]: df2 = DataFrame({'a' : [0, 1, 1], 'b' : [1, 1, 0] }, dtype=bool)
In [305]: df1 & df2
Out[305]:
a b
0 False False
1 False True
2 True False
In [306]: df1 | df2
Out[306]:
a b
0 True True
1 True True
2 True True
In [307]: df1 ^ df2
Out[307]:
a b
0 True True
1 True False
2 False True
In [308]: -df1
Out[308]:
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 [309]: df[:5].T
Out[309]:
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 [310]: np.exp(df)
Out[310]:
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 [311]: np.asarray(df)
Out[311]:
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 [312]: df.T.dot(df)
Out[312]:
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 [313]: s1 = Series(np.arange(5,10))
In [314]: s1.dot(s1)
Out[314]: 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 [315]: baseball = read_csv('data/baseball.csv')
In [316]: 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 [317]: 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 [318]: baseball.dtypes
Out[318]:
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 [319]: baseball.get_dtype_counts()
Out[319]:
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 [320]: df = DataFrame({'foo1' : np.random.randn(5),
.....: 'foo2' : np.random.randn(5)})
In [321]: df
Out[321]:
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 [322]: df.foo1
Out[322]:
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 [323]: wp = Panel(randn(2, 5, 4), items=['Item1', 'Item2'],
.....: major_axis=DateRange('1/1/2000', periods=5),
.....: minor_axis=['A', 'B', 'C', 'D'])
In [324]: wp
Out[324]:
<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 [325]: data = {'Item1' : DataFrame(randn(4, 3)),
.....: 'Item2' : DataFrame(randn(4, 2))}
In [326]: Panel(data)
Out[326]:
<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 [327]: Panel.from_dict(data, orient='minor')
Out[327]:
<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.
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 [328]: midx = MultiIndex(levels=[['one', 'two'], ['x','y']], labels=[[1,1,0,0],[1,0,1,0]])
In [329]: df = DataFrame({'A' : [1, 2, 3, 4], 'B': [5, 6, 7, 8]}, index=midx)
In [330]: df.to_panel()
Out[330]:
<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 [331]: wp['Item1']
Out[331]:
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 [332]: 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 [333]: wp['Item1']
Out[333]:
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 [334]: wp.major_xs(wp.major_axis[2])
Out[334]:
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 [335]: wp.minor_axis
Out[335]: Index([A, B, C, D], dtype=object)
In [336]: wp.minor_xs('C')
Out[336]:
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