{"id":147,"date":"2013-03-31T23:48:49","date_gmt":"2013-04-01T04:48:49","guid":{"rendered":"http:\/\/homepages.uc.edu\/~yaozo\/wordpress\/?p=147"},"modified":"2013-03-31T23:48:49","modified_gmt":"2013-04-01T04:48:49","slug":"intro-to-data-structures","status":"publish","type":"post","link":"https:\/\/zhuoyao.net\/index.php\/2013\/03\/31\/intro-to-data-structures\/","title":{"rendered":"Intro to Data Structures"},"content":{"rendered":"<p>We\u2019ll 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:<\/p>\n<div>\n<div>\n<pre>In [477]: import numpy as np\n\n# will use a lot in examples\nIn [478]: randn = np.random.randn\n\nIn [479]: from pandas import *<\/pre>\n<\/div>\n<\/div>\n<p>Here is a basic tenet to keep in mind:\u00a0<strong>data alignment is intrinsic<\/strong>. The link between labels and data will not be broken unless done so explicitly by you.<\/p>\n<p>We\u2019ll give a brief intro to the data structures, then consider all of the broad categories of functionality and methods in separate sections.<\/p>\n<p>When using pandas, we recommend the following import convention:<\/p>\n<div>\n<div>\n<pre>import pandas as pd<\/pre>\n<\/div>\n<\/div>\n<div id=\"series\">\n<h2>Series<\/h2>\n<p><tt>Series<\/tt>\u00a0is 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\u00a0<strong>index<\/strong>. The basic method to create a Series is to call:<\/p>\n<div>\n<div>\n<pre>&gt;&gt;&gt; s = Series(data, index=index)<\/pre>\n<\/div>\n<\/div>\n<p>Here,\u00a0<tt>data<\/tt>\u00a0can be many different things:<\/p>\n<blockquote>\n<ul>\n<li>a Python dict<\/li>\n<li>an ndarray<\/li>\n<li>a scalar value (like 5)<\/li>\n<\/ul>\n<\/blockquote>\n<p>The passed\u00a0<strong>index<\/strong>\u00a0is a list of axis labels. Thus, this separates into a few cases depending on what\u00a0<strong>data is<\/strong>:<\/p>\n<p><strong>From ndarray<\/strong><\/p>\n<p>If\u00a0<tt>data<\/tt>\u00a0is an ndarray,\u00a0<strong>index<\/strong>\u00a0must be the same length as\u00a0<strong>data<\/strong>. If no index is passed, one will be created having values\u00a0<tt>[0,\u00a0...,\u00a0len(data)\u00a0-\u00a01]<\/tt>.<\/p>\n<div>\n<div>\n<pre>In [480]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])\n\nIn [481]: s\nOut[481]: \na    0.405\nb    0.577\nc   -1.715\nd   -1.039\ne   -0.371\ndtype: float64\n\nIn [482]: s.index\nOut[482]: Index([a, b, c, d, e], dtype=object)\n\nIn [483]: Series(randn(5))\nOut[483]: \n0   -1.158\n1   -1.344\n2    0.845\n3    1.076\n4   -0.109\ndtype: float64<\/pre>\n<\/div>\n<\/div>\n<div>\n<p>Note<\/p>\n<p>Starting in v0.8.0, pandas supports non-unique index values. In previous version, if the index values are not unique an exception will\u00a0<strong>not<\/strong>\u00a0be raised immediately, but attempting any operation involving the index will later result in an exception. In other words, the Index object containing the labels \u201clazily\u201d 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).<\/p>\n<\/div>\n<p><strong>From dict<\/strong><\/p>\n<p>If\u00a0<tt>data<\/tt>\u00a0is a dict, if\u00a0<strong>index<\/strong>\u00a0is 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.<\/p>\n<div>\n<div>\n<pre>In [484]: d = {'a' : 0., 'b' : 1., 'c' : 2.}\n\nIn [485]: Series(d)\nOut[485]: \na    0\nb    1\nc    2\ndtype: float64\n\nIn [486]: Series(d, index=['b', 'c', 'd', 'a'])\nOut[486]: \nb     1\nc     2\nd   NaN\na     0\ndtype: float64<\/pre>\n<\/div>\n<\/div>\n<div>\n<p>Note<\/p>\n<p>NaN (not a number) is the standard missing data marker used in pandas<\/p>\n<\/div>\n<p><strong>From scalar value<\/strong>\u00a0If\u00a0<tt>data<\/tt>\u00a0is a scalar value, an index must be provided. The value will be repeated to match the length of\u00a0<strong>index<\/strong><\/p>\n<div>\n<div>\n<pre>In [487]: Series(5., index=['a', 'b', 'c', 'd', 'e'])\nOut[487]: \na    5\nb    5\nc    5\nd    5\ne    5\ndtype: float64<\/pre>\n<\/div>\n<\/div>\n<div id=\"series-is-ndarray-like\">\n<h3>Series is ndarray-like<\/h3>\n<p>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.<\/p>\n<div>\n<div>\n<pre>In [488]: s[0]\nOut[488]: 0.40470521868023651\n\nIn [489]: s[:3]\nOut[489]: \na    0.405\nb    0.577\nc   -1.715\ndtype: float64\n\nIn [490]: s[s &gt; s.median()]\nOut[490]: \na    0.405\nb    0.577\ndtype: float64\n\nIn [491]: s[[4, 3, 1]]\nOut[491]: \ne   -0.371\nd   -1.039\nb    0.577\ndtype: float64\n\nIn [492]: np.exp(s)\nOut[492]: \na    1.499\nb    1.781\nc    0.180\nd    0.354\ne    0.690\ndtype: float64<\/pre>\n<\/div>\n<\/div>\n<p>We will address array-based indexing in a separate\u00a0<a href=\"http:\/\/pandas.pydata.org\/pandas-docs\/dev\/indexing.html#indexing\"><em>section<\/em><\/a>.<\/p>\n<\/div>\n<div id=\"series-is-dict-like\">\n<h3>Series is dict-like<\/h3>\n<p>A Series is like a fixed-size dict in that you can get and set values by index label:<\/p>\n<div>\n<div>\n<pre>In [493]: s['a']\nOut[493]: 0.40470521868023651\n\nIn [494]: s['e'] = 12.\n\nIn [495]: s\nOut[495]: \na     0.405\nb     0.577\nc    -1.715\nd    -1.039\ne    12.000\ndtype: float64\n\nIn [496]: 'e' in s\nOut[496]: True\n\nIn [497]: 'f' in s\nOut[497]: False<\/pre>\n<\/div>\n<\/div>\n<p>If a label is not contained, an exception is raised:<\/p>\n<div>\n<div>\n<pre>&gt;&gt;&gt; s['f']\nKeyError: 'f'<\/pre>\n<\/div>\n<\/div>\n<p>Using the\u00a0<tt>get<\/tt>\u00a0method, a missing label will return None or specified default:<\/p>\n<div>\n<div>\n<pre>In [498]: s.get('f')\n\nIn [499]: s.get('f', np.nan)\nOut[499]: nan<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"vectorized-operations-and-label-alignment-with-series\">\n<h3>Vectorized operations and label alignment with Series<\/h3>\n<p>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.<\/p>\n<div>\n<div>\n<pre>In [500]: s + s\nOut[500]: \na     0.809\nb     1.154\nc    -3.430\nd    -2.079\ne    24.000\ndtype: float64\n\nIn [501]: s * 2\nOut[501]: \na     0.809\nb     1.154\nc    -3.430\nd    -2.079\ne    24.000\ndtype: float64\n\nIn [502]: np.exp(s)\nOut[502]: \na         1.499\nb         1.781\nc         0.180\nd         0.354\ne    162754.791\ndtype: float64<\/pre>\n<\/div>\n<\/div>\n<p>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.<\/p>\n<div>\n<div>\n<pre>In [503]: s[1:] + s[:-1]\nOut[503]: \na      NaN\nb    1.154\nc   -3.430\nd   -2.079\ne      NaN\ndtype: float64<\/pre>\n<\/div>\n<\/div>\n<p>The result of an operation between unaligned Series will have the\u00a0<strong>union<\/strong>\u00a0of 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.<\/p>\n<div>\n<p>Note<\/p>\n<p>In general, we chose to make the default result of operations between differently indexed objects yield the\u00a0<strong>union<\/strong>\u00a0of 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<strong>dropna<\/strong>\u00a0function.<\/p>\n<\/div>\n<\/div>\n<div id=\"name-attribute\">\n<h3>Name attribute<\/h3>\n<p id=\"dsintro-name-attribute\">Series can also have a\u00a0<tt>name<\/tt>\u00a0attribute:<\/p>\n<div>\n<div>\n<pre>In [504]: s = Series(np.random.randn(5), name='something')\n\nIn [505]: s\nOut[505]: \n0    1.644\n1   -1.469\n2    0.357\n3   -0.675\n4   -1.777\nName: something, dtype: float64\n\nIn [506]: s.name\nOut[506]: 'something'<\/pre>\n<\/div>\n<\/div>\n<p>The Series\u00a0<tt>name<\/tt>\u00a0will be assigned automatically in many cases, in particular when taking 1D slices of DataFrame as you will see below.<\/p>\n<\/div>\n<\/div>\n<div id=\"dataframe\">\n<h2>DataFrame<\/h2>\n<p><strong>DataFrame<\/strong>\u00a0is 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:<\/p>\n<blockquote>\n<ul>\n<li>Dict of 1D ndarrays, lists, dicts, or Series<\/li>\n<li>2-D numpy.ndarray<\/li>\n<li><a href=\"http:\/\/docs.scipy.org\/doc\/numpy\/user\/basics.rec.html\">Structured or record<\/a>\u00a0ndarray<\/li>\n<li>A\u00a0<tt>Series<\/tt><\/li>\n<li>Another\u00a0<tt>DataFrame<\/tt><\/li>\n<\/ul>\n<\/blockquote>\n<p>Along with the data, you can optionally pass\u00a0<strong>index<\/strong>\u00a0(row labels) and\u00a0<strong>columns<\/strong>\u00a0(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.<\/p>\n<p>If axis labels are not passed, they will be constructed from the input data based on common sense rules.<\/p>\n<div id=\"from-dict-of-series-or-dicts\">\n<h3>From dict of Series or dicts<\/h3>\n<p>The result\u00a0<strong>index<\/strong>\u00a0will be the\u00a0<strong>union<\/strong>\u00a0of 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.<\/p>\n<div>\n<div>\n<pre>In [507]: d = {'one' : Series([1., 2., 3.], index=['a', 'b', 'c']),\n   .....:      'two' : Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}\n   .....:\n\nIn [508]: df = DataFrame(d)\n\nIn [509]: df\nOut[509]: \n   one  two\na    1    1\nb    2    2\nc    3    3\nd  NaN    4\n\nIn [510]: DataFrame(d, index=['d', 'b', 'a'])\nOut[510]: \n   one  two\nd  NaN    4\nb    2    2\na    1    1\n\nIn [511]: DataFrame(d, index=['d', 'b', 'a'], columns=['two', 'three'])\nOut[511]: \n   two three\nd    4   NaN\nb    2   NaN\na    1   NaN<\/pre>\n<\/div>\n<\/div>\n<p>The row and column labels can be accessed respectively by accessing the\u00a0<strong>index<\/strong>\u00a0and<strong>columns<\/strong>\u00a0attributes:<\/p>\n<div>\n<p>Note<\/p>\n<p>When a particular set of columns is passed along with a dict of data, the passed columns override the keys in the dict.<\/p>\n<\/div>\n<div>\n<div>\n<pre>In [512]: df.index\nOut[512]: Index([a, b, c, d], dtype=object)\n\nIn [513]: df.columns\nOut[513]: Index([one, two], dtype=object)<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"from-dict-of-ndarrays-lists\">\n<h3>From dict of ndarrays \/ lists<\/h3>\n<p>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\u00a0<tt>range(n)<\/tt>, where\u00a0<tt>n<\/tt>\u00a0is the array length.<\/p>\n<div>\n<div>\n<pre>In [514]: d = {'one' : [1., 2., 3., 4.],\n   .....:      'two' : [4., 3., 2., 1.]}\n   .....:\n\nIn [515]: DataFrame(d)\nOut[515]: \n   one  two\n0    1    4\n1    2    3\n2    3    2\n3    4    1\n\nIn [516]: DataFrame(d, index=['a', 'b', 'c', 'd'])\nOut[516]: \n   one  two\na    1    4\nb    2    3\nc    3    2\nd    4    1<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"from-structured-or-record-array\">\n<h3>From structured or record array<\/h3>\n<p>This case is handled identically to a dict of arrays.<\/p>\n<div>\n<div>\n<pre>In [517]: data = np.zeros((2,),dtype=[('A', 'i4'),('B', 'f4'),('C', 'a10')])\n\nIn [518]: data[:] = [(1,2.,'Hello'),(2,3.,\"World\")]\n\nIn [519]: DataFrame(data)\nOut[519]: \n   A  B      C\n0  1  2  Hello\n1  2  3  World\n\nIn [520]: DataFrame(data, index=['first', 'second'])\nOut[520]: \n        A  B      C\nfirst   1  2  Hello\nsecond  2  3  World\n\nIn [521]: DataFrame(data, columns=['C', 'A', 'B'])\nOut[521]: \n       C  A  B\n0  Hello  1  2\n1  World  2  3<\/pre>\n<\/div>\n<\/div>\n<div>\n<p>Note<\/p>\n<p>DataFrame is not intended to work exactly like a 2-dimensional NumPy ndarray.<\/p>\n<\/div>\n<\/div>\n<div id=\"from-a-list-of-dicts\">\n<h3>From a list of dicts<\/h3>\n<div>\n<div>\n<pre>In [522]: data2 = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}]\n\nIn [523]: DataFrame(data2)\nOut[523]: \n   a   b   c\n0  1   2 NaN\n1  5  10  20\n\nIn [524]: DataFrame(data2, index=['first', 'second'])\nOut[524]: \n        a   b   c\nfirst   1   2 NaN\nsecond  5  10  20\n\nIn [525]: DataFrame(data2, columns=['a', 'b'])\nOut[525]: \n   a   b\n0  1   2\n1  5  10<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"from-a-series\">\n<h3>From a Series<\/h3>\n<p>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).<\/p>\n<p><strong>Missing Data<\/strong><\/p>\n<p>Much more will be said on this topic in the\u00a0<a href=\"http:\/\/pandas.pydata.org\/pandas-docs\/dev\/missing_data.html#missing-data\"><em>Missing data<\/em><\/a>\u00a0section. To construct a DataFrame with missing data, use\u00a0<tt>np.nan<\/tt>\u00a0for those values which are missing. Alternatively, you may pass a\u00a0<tt>numpy.MaskedArray<\/tt>\u00a0as the data argument to the DataFrame constructor, and its masked entries will be considered missing.<\/p>\n<\/div>\n<div id=\"alternate-constructors\">\n<h3>Alternate Constructors<\/h3>\n<p id=\"basics-dataframe-from-dict\"><strong>DataFrame.from_dict<\/strong><\/p>\n<p><tt>DataFrame.from_dict<\/tt>\u00a0takes a dict of dicts or a dict of array-like sequences and returns a DataFrame. It operates like the\u00a0<tt>DataFrame<\/tt>\u00a0constructor except for the\u00a0<tt>orient<\/tt>\u00a0parameter which is\u00a0<tt>'columns'<\/tt>\u00a0by default, but which can be set to\u00a0<tt>'index'<\/tt>\u00a0in order to use the dict keys as row labels.<\/p>\n<p id=\"basics-dataframe-from-records\"><strong>DataFrame.from_records<\/strong><\/p>\n<p><tt>DataFrame.from_records<\/tt>\u00a0takes a list of tuples or an ndarray with structured dtype. Works analogously to the normal\u00a0<tt>DataFrame<\/tt>\u00a0constructor, except that index maybe be a specific field of the structured dtype to use as the index. For example:<\/p>\n<div>\n<div>\n<pre>In [526]: data\nOut[526]: \narray([(1, 2.0, 'Hello'), (2, 3.0, 'World')], \n      dtype=[('A', '&lt;i4'), ('B', '&lt;f4'), ('C', '|S10')])\n\nIn [527]: DataFrame.from_records(data, index='C')\nOut[527]: \n       A  B\nC          \nHello  1  2\nWorld  2  3<\/pre>\n<\/div>\n<\/div>\n<p id=\"basics-dataframe-from-items\"><strong>DataFrame.from_items<\/strong><\/p>\n<p><tt>DataFrame.from_items<\/tt>\u00a0works analogously to the form of the\u00a0<tt>dict<\/tt>\u00a0constructor that takes a sequence of\u00a0<tt>(key,\u00a0value)<\/tt>\u00a0pairs, where the keys are column (or row, in the case of<tt>orient='index'<\/tt>) 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:<\/p>\n<div>\n<div>\n<pre>In [528]: DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])])\nOut[528]: \n   A  B\n0  1  4\n1  2  5\n2  3  6<\/pre>\n<\/div>\n<\/div>\n<p>If you pass\u00a0<tt>orient='index'<\/tt>, the keys will be the row labels. But in this case you must also pass the desired column names:<\/p>\n<div>\n<div>\n<pre>In [529]: DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])],\n   .....:                      orient='index', columns=['one', 'two', 'three'])\n   .....:\nOut[529]: \n   one  two  three\nA    1    2      3\nB    4    5      6<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"column-selection-addition-deletion\">\n<h3>Column selection, addition, deletion<\/h3>\n<p>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:<\/p>\n<div>\n<div>\n<pre>In [530]: df['one']\nOut[530]: \na     1\nb     2\nc     3\nd   NaN\nName: one, dtype: float64\n\nIn [531]: df['three'] = df['one'] * df['two']\n\nIn [532]: df['flag'] = df['one'] &gt; 2\n\nIn [533]: df\nOut[533]: \n   one  two  three   flag\na    1    1      1  False\nb    2    2      4  False\nc    3    3      9   True\nd  NaN    4    NaN  False<\/pre>\n<\/div>\n<\/div>\n<p>Columns can be deleted or popped like with a dict:<\/p>\n<div>\n<div>\n<pre>In [534]: del df['two']\n\nIn [535]: three = df.pop('three')\n\nIn [536]: df\nOut[536]: \n   one   flag\na    1  False\nb    2  False\nc    3   True\nd  NaN  False<\/pre>\n<\/div>\n<\/div>\n<p>When inserting a scalar value, it will naturally be propagated to fill the column:<\/p>\n<div>\n<div>\n<pre>In [537]: df['foo'] = 'bar'\n\nIn [538]: df\nOut[538]: \n   one   flag  foo\na    1  False  bar\nb    2  False  bar\nc    3   True  bar\nd  NaN  False  bar<\/pre>\n<\/div>\n<\/div>\n<p>When inserting a Series that does not have the same index as the DataFrame, it will be conformed to the DataFrame\u2019s index:<\/p>\n<div>\n<div>\n<pre>In [539]: df['one_trunc'] = df['one'][:2]\n\nIn [540]: df\nOut[540]: \n   one   flag  foo  one_trunc\na    1  False  bar          1\nb    2  False  bar          2\nc    3   True  bar        NaN\nd  NaN  False  bar        NaN<\/pre>\n<\/div>\n<\/div>\n<p>You can insert raw ndarrays but their length must match the length of the DataFrame\u2019s index.<\/p>\n<p>By default, columns get inserted at the end. The\u00a0<tt>insert<\/tt>\u00a0function is available to insert at a particular location in the columns:<\/p>\n<div>\n<div>\n<pre>In [541]: df.insert(1, 'bar', df['one'])\n\nIn [542]: df\nOut[542]: \n   one  bar   flag  foo  one_trunc\na    1    1  False  bar          1\nb    2    2  False  bar          2\nc    3    3   True  bar        NaN\nd  NaN  NaN  False  bar        NaN<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"indexing-selection\">\n<h3>Indexing \/ Selection<\/h3>\n<p>The basics of indexing are as follows:<\/p>\n<table border=\"1\">\n<colgroup>\n<col width=\"50%\" \/>\n<col width=\"33%\" \/>\n<col width=\"17%\" \/><\/colgroup>\n<thead valign=\"bottom\">\n<tr>\n<th>Operation<\/th>\n<th>Syntax<\/th>\n<th>Result<\/th>\n<\/tr>\n<\/thead>\n<tbody valign=\"top\">\n<tr>\n<td>Select column<\/td>\n<td><tt>df[col]<\/tt><\/td>\n<td>Series<\/td>\n<\/tr>\n<tr>\n<td>Select row by label<\/td>\n<td><tt>df.loc[label]<\/tt><\/td>\n<td>Series<\/td>\n<\/tr>\n<tr>\n<td>Select row by integer location<\/td>\n<td><tt>df.iloc[loc]<\/tt><\/td>\n<td>Series<\/td>\n<\/tr>\n<tr>\n<td>Slice rows<\/td>\n<td><tt>df[5:10]<\/tt><\/td>\n<td>DataFrame<\/td>\n<\/tr>\n<tr>\n<td>Select rows by boolean vector<\/td>\n<td><tt>df[bool_vec]<\/tt><\/td>\n<td>DataFrame<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Row selection, for example, returns a Series whose index is the columns of the DataFrame:<\/p>\n<div>\n<div>\n<pre>In [543]: df.loc['b']\nOut[543]: \none              2\nbar              2\nflag         False\nfoo            bar\none_trunc        2\nName: b, dtype: object\n\nIn [544]: df.iloc[2]\nOut[544]: \none             3\nbar             3\nflag         True\nfoo           bar\none_trunc     NaN\nName: c, dtype: object<\/pre>\n<\/div>\n<\/div>\n<p>For a more exhaustive treatment of more sophisticated label-based indexing and slicing, see the\u00a0<a href=\"http:\/\/pandas.pydata.org\/pandas-docs\/dev\/indexing.html#indexing\"><em>section on indexing<\/em><\/a>. We will address the fundamentals of reindexing \/ conforming to new sets of lables in the\u00a0<a href=\"http:\/\/pandas.pydata.org\/pandas-docs\/dev\/basics.html#basics-reindexing\"><em>section on reindexing<\/em><\/a>.<\/p>\n<\/div>\n<div id=\"data-alignment-and-arithmetic\">\n<h3>Data alignment and arithmetic<\/h3>\n<p>Data alignment between DataFrame objects automatically align on\u00a0<strong>both the columns and the index (row labels)<\/strong>. Again, the resulting object will have the union of the column and row labels.<\/p>\n<div>\n<div>\n<pre>In [545]: df = DataFrame(randn(10, 4), columns=['A', 'B', 'C', 'D'])\n\nIn [546]: df2 = DataFrame(randn(7, 3), columns=['A', 'B', 'C'])\n\nIn [547]: df + df2\nOut[547]: \n       A      B      C   D\n0 -1.697 -1.416  0.316 NaN\n1  0.224  0.328  0.597 NaN\n2 -2.033  0.276  0.955 NaN\n3  1.833  2.119  1.517 NaN\n4  0.177  0.256  1.115 NaN\n5 -3.007 -1.446 -2.142 NaN\n6  0.026 -3.157  0.781 NaN\n7    NaN    NaN    NaN NaN\n8    NaN    NaN    NaN NaN\n9    NaN    NaN    NaN NaN<\/pre>\n<\/div>\n<\/div>\n<p>When doing an operation between DataFrame and Series, the default behavior is to align the Series\u00a0<strong>index<\/strong>\u00a0on the DataFrame\u00a0<strong>columns<\/strong>, thus\u00a0<a href=\"http:\/\/docs.scipy.org\/doc\/numpy\/user\/basics.broadcasting.html\">broadcasting<\/a>\u00a0row-wise. For example:<\/p>\n<div>\n<div>\n<pre>In [548]: df - df.iloc[0]\nOut[548]: \n       A      B      C      D\n0  0.000  0.000  0.000  0.000\n1  0.497  1.281 -0.776 -0.283\n2  0.046  2.190  0.392 -1.483\n3  3.535  2.726  0.927 -1.447\n4  0.743  1.705  0.400 -0.145\n5  0.142  1.218 -1.601  0.853\n6 -0.468 -0.119  1.194  0.748\n7  1.539  2.170 -2.625  0.698\n8 -1.038  0.885 -0.492  0.269\n9 -0.250  0.068  0.356 -1.558<\/pre>\n<\/div>\n<\/div>\n<p>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:<\/p>\n<div>\n<div>\n<pre>In [549]: index = date_range('1\/1\/2000', periods=8)\n\nIn [550]: df = DataFrame(randn(8, 3), index=index,\n   .....:                columns=['A', 'B', 'C'])\n   .....:\n\nIn [551]: df\nOut[551]: \n                A      B      C\n2000-01-01 -0.345  1.314  0.691\n2000-01-02  0.996  2.397  0.015\n2000-01-03  3.357 -0.317 -1.236\n2000-01-04  0.896 -0.488 -0.082\n2000-01-05 -2.183  0.380  0.085\n2000-01-06  0.432  1.520 -0.494\n2000-01-07  0.600  0.274  0.133\n2000-01-08 -0.024  2.410  1.451\n\nIn [552]: type(df['A'])\nOut[552]: pandas.core.series.TimeSeries\n\nIn [553]: df - df['A']\nOut[553]: \n            A      B      C\n2000-01-01  0  1.660  1.036\n2000-01-02  0  1.401 -0.981\n2000-01-03  0 -3.675 -4.594\n2000-01-04  0 -1.384 -0.978\n2000-01-05  0  2.563  2.268\n2000-01-06  0  1.088 -0.926\n2000-01-07  0 -0.326 -0.467\n2000-01-08  0  2.434  1.474<\/pre>\n<\/div>\n<\/div>\n<p>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:<\/p>\n<div>\n<div>\n<pre>In [554]: (df.T - df['A']).T\nOut[554]: \n            A      B      C\n2000-01-01  0  1.660  1.036\n2000-01-02  0  1.401 -0.981\n2000-01-03  0 -3.675 -4.594\n2000-01-04  0 -1.384 -0.978\n2000-01-05  0  2.563  2.268\n2000-01-06  0  1.088 -0.926\n2000-01-07  0 -0.326 -0.467\n2000-01-08  0  2.434  1.474<\/pre>\n<\/div>\n<\/div>\n<p>For explicit control over the matching and broadcasting behavior, see the section on\u00a0<a href=\"http:\/\/pandas.pydata.org\/pandas-docs\/dev\/basics.html#basics-binop\"><em>flexible binary operations<\/em><\/a>.<\/p>\n<p>Operations with scalars are just as you would expect:<\/p>\n<div>\n<div>\n<pre>In [555]: df * 5 + 2\nOut[555]: \n                 A       B      C\n2000-01-01   0.273   8.571  5.453\n2000-01-02   6.979  13.984  2.074\n2000-01-03  18.787   0.413 -4.181\n2000-01-04   6.481  -0.438  1.589\n2000-01-05  -8.915   3.902  2.424\n2000-01-06   4.162   9.600 -0.468\n2000-01-07   5.001   3.371  2.664\n2000-01-08   1.882  14.051  9.253\n\nIn [556]: 1 \/ df\nOut[556]: \n                 A      B       C\n2000-01-01  -2.896  0.761   1.448\n2000-01-02   1.004  0.417  67.245\n2000-01-03   0.298 -3.150  -0.809\n2000-01-04   1.116 -2.051 -12.159\n2000-01-05  -0.458  2.629  11.786\n2000-01-06   2.313  0.658  -2.026\n2000-01-07   1.666  3.647   7.525\n2000-01-08 -42.215  0.415   0.689\n\nIn [557]: df ** 4\nOut[557]: \n                    A       B          C\n2000-01-01  1.422e-02   2.983  2.274e-01\n2000-01-02  9.832e-01  33.000  4.891e-08\n2000-01-03  1.271e+02   0.010  2.336e+00\n2000-01-04  6.450e-01   0.057  4.574e-05\n2000-01-05  2.271e+01   0.021  5.182e-05\n2000-01-06  3.495e-02   5.338  5.939e-02\n2000-01-07  1.298e-01   0.006  3.118e-04\n2000-01-08  3.149e-07  33.744  4.427e+00<\/pre>\n<\/div>\n<\/div>\n<p id=\"dsintro-boolean\">Boolean operators work as well:<\/p>\n<div>\n<div>\n<pre>In [558]: df1 = DataFrame({'a' : [1, 0, 1], 'b' : [0, 1, 1] }, dtype=bool)\n\nIn [559]: df2 = DataFrame({'a' : [0, 1, 1], 'b' : [1, 1, 0] }, dtype=bool)\n\nIn [560]: df1 &amp; df2\nOut[560]: \n       a      b\n0  False  False\n1  False   True\n2   True  False\n\nIn [561]: df1 | df2\nOut[561]: \n      a     b\n0  True  True\n1  True  True\n2  True  True\n\nIn [562]: df1 ^ df2\nOut[562]: \n       a      b\n0   True   True\n1   True  False\n2  False   True\n\nIn [563]: -df1\nOut[563]: \n       a      b\n0  False   True\n1   True  False\n2  False  False<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"transposing\">\n<h3>Transposing<\/h3>\n<p>To transpose, access the\u00a0<tt>T<\/tt>\u00a0attribute (also the\u00a0<tt>transpose<\/tt>\u00a0function), similar to an ndarray:<\/p>\n<div>\n<div>\n<pre># only show the first 5 rows\nIn [564]: df[:5].T\nOut[564]: \n   2000-01-01  2000-01-02  2000-01-03  2000-01-04  2000-01-05\nA      -0.345       0.996       3.357       0.896      -2.183\nB       1.314       2.397      -0.317      -0.488       0.380\nC       0.691       0.015      -1.236      -0.082       0.085<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"dataframe-interoperability-with-numpy-functions\">\n<h3>DataFrame interoperability with NumPy functions<\/h3>\n<p id=\"dsintro-numpy-interop\">Elementwise NumPy ufuncs (log, exp, sqrt, &#8230;) and various other NumPy functions can be used with no issues on DataFrame, assuming the data within are numeric:<\/p>\n<div>\n<div>\n<pre>In [565]: np.exp(df)\nOut[565]: \n                 A       B      C\n2000-01-01   0.708   3.722  1.995\n2000-01-02   2.707  10.988  1.015\n2000-01-03  28.715   0.728  0.290\n2000-01-04   2.450   0.614  0.921\n2000-01-05   0.113   1.463  1.089\n2000-01-06   1.541   4.572  0.610\n2000-01-07   1.822   1.316  1.142\n2000-01-08   0.977  11.136  4.265\n\nIn [566]: np.asarray(df)\nOut[566]: \narray([[-0.3454,  1.3142,  0.6906],\n       [ 0.9958,  2.3968,  0.0149],\n       [ 3.3574, -0.3174, -1.2363],\n       [ 0.8962, -0.4876, -0.0822],\n       [-2.1829,  0.3804,  0.0848],\n       [ 0.4324,  1.52  , -0.4937],\n       [ 0.6002,  0.2742,  0.1329],\n       [-0.0237,  2.4102,  1.4505]])<\/pre>\n<\/div>\n<\/div>\n<p>The dot method on DataFrame implements matrix multiplication:<\/p>\n<div>\n<div>\n<pre>In [567]: df.T.dot(df)\nOut[567]: \n        A       B      C\nA  18.499   0.364 -4.801\nB   0.364  16.149  4.190\nC  -4.801   4.190  4.385<\/pre>\n<\/div>\n<\/div>\n<p>Similarly, the dot method on Series implements dot product:<\/p>\n<div>\n<div>\n<pre>In [568]: s1 = Series(np.arange(5,10))\n\nIn [569]: s1.dot(s1)\nOut[569]: 255<\/pre>\n<\/div>\n<\/div>\n<p>DataFrame is not intended to be a drop-in replacement for ndarray as its indexing semantics are quite different in places from a matrix.<\/p>\n<\/div>\n<div id=\"console-display\">\n<h3>Console display<\/h3>\n<p>For very large DataFrame objects, only a summary will be printed to the console (here I am reading a CSV version of the\u00a0<strong>baseball<\/strong>\u00a0dataset from the\u00a0<strong>plyr<\/strong>\u00a0R package):<\/p>\n<div>\n<div>\n<pre>In [570]: baseball = read_csv('data\/baseball.csv')\n\nIn [571]: print baseball\n&lt;class 'pandas.core.frame.DataFrame'&gt;\nInt64Index: 100 entries, 88641 to 89534\nData columns (total 22 columns):\nid       100  non-null values\nyear     100  non-null values\nstint    100  non-null values\nteam     100  non-null values\nlg       100  non-null values\ng        100  non-null values\nab       100  non-null values\nr        100  non-null values\nh        100  non-null values\nX2b      100  non-null values\nX3b      100  non-null values\nhr       100  non-null values\nrbi      100  non-null values\nsb       100  non-null values\ncs       100  non-null values\nbb       100  non-null values\nso       100  non-null values\nibb      100  non-null values\nhbp      100  non-null values\nsh       100  non-null values\nsf       100  non-null values\ngidp     100  non-null values\ndtypes: float64(9), int64(10), object(3)<\/pre>\n<\/div>\n<\/div>\n<p>However, using\u00a0<tt>to_string<\/tt>\u00a0will return a string representation of the DataFrame in tabular form, though it won\u2019t always fit the console width:<\/p>\n<div>\n<div>\n<pre>In [572]: print baseball.iloc[-20:, :12].to_string()\n              id  year  stint team  lg    g   ab   r    h  X2b  X3b  hr\n89474  finlest01  2007      1  COL  NL   43   94   9   17    3    0   1\n89480  embreal01  2007      1  OAK  AL    4    0   0    0    0    0   0\n89481  edmonji01  2007      1  SLN  NL  117  365  39   92   15    2  12\n89482  easleda01  2007      1  NYN  NL   76  193  24   54    6    0  10\n89489  delgaca01  2007      1  NYN  NL  139  538  71  139   30    0  24\n89493  cormirh01  2007      1  CIN  NL    6    0   0    0    0    0   0\n89494  coninje01  2007      2  NYN  NL   21   41   2    8    2    0   0\n89495  coninje01  2007      1  CIN  NL   80  215  23   57   11    1   6\n89497  clemero02  2007      1  NYA  AL    2    2   0    1    0    0   0\n89498  claytro01  2007      2  BOS  AL    8    6   1    0    0    0   0\n89499  claytro01  2007      1  TOR  AL   69  189  23   48   14    0   1\n89501  cirilje01  2007      2  ARI  NL   28   40   6    8    4    0   0\n89502  cirilje01  2007      1  MIN  AL   50  153  18   40    9    2   2\n89521  bondsba01  2007      1  SFN  NL  126  340  75   94   14    0  28\n89523  biggicr01  2007      1  HOU  NL  141  517  68  130   31    3  10\n89525  benitar01  2007      2  FLO  NL   34    0   0    0    0    0   0\n89526  benitar01  2007      1  SFN  NL   19    0   0    0    0    0   0\n89530  ausmubr01  2007      1  HOU  NL  117  349  38   82   16    3   3\n89533   aloumo01  2007      1  NYN  NL   87  328  51  112   19    1  13\n89534  alomasa02  2007      1  NYN  NL    8   22   1    3    1    0   0<\/pre>\n<\/div>\n<\/div>\n<p>New since 0.10.0, wide DataFrames will now be printed across multiple rows by default:<\/p>\n<div>\n<div>\n<pre>In [573]: DataFrame(randn(3, 12))\nOut[573]: \n         0         1         2         3         4         5         6         7   \\\n0  0.206053 -0.251905 -2.213588  1.063327  1.266143  0.299368 -0.863838  0.408204   \n1  1.262731  1.289997  0.082423 -0.055758  0.536580 -0.489682  0.369374 -0.034571   \n2  1.126203 -0.977349  1.474071 -0.064034 -1.282782  0.781836 -1.071357  0.441153   \n         8         9         10        11  \n0 -1.048089 -0.025747 -0.988387  0.094055  \n1 -2.484478 -0.281461  0.030711  0.109121  \n2  2.353925  0.583787  0.221471 -0.744471<\/pre>\n<\/div>\n<\/div>\n<p>You can change how much to print on a single row by setting the\u00a0<tt>line_width<\/tt>\u00a0option:<\/p>\n<div>\n<div>\n<pre>In [574]: set_option('line_width', 40) # default is 80\n\nIn [575]: DataFrame(randn(3, 12))\nOut[575]: \n         0         1         2         3   \\\n0  0.758527  1.729689 -0.964980 -0.845696   \n1  1.171216  0.520260 -1.197071 -1.066969   \n2  0.473424 -0.242861 -0.014805 -0.284319   \n         4         5         6         7   \\\n0 -1.340896  1.846883 -1.328865  1.682706   \n1 -0.303421 -0.858447  0.306996 -0.028665   \n2  0.650776 -1.461665 -1.137707 -0.891060   \n         8         9         10        11  \n0 -1.717693  0.888782  0.228440  0.901805  \n1  0.384316  1.574159  1.588931  0.476720  \n2 -0.693921  1.613616  0.464000  0.227371<\/pre>\n<\/div>\n<\/div>\n<p>You can also disable this feature via the\u00a0<tt>expand_frame_repr<\/tt>\u00a0option:<\/p>\n<div>\n<div>\n<pre>In [576]: set_option('expand_frame_repr', False)\n\nIn [577]: DataFrame(randn(3, 12))\nOut[577]: \n&lt;class 'pandas.core.frame.DataFrame'&gt;\nInt64Index: 3 entries, 0 to 2\nData columns (total 12 columns):\n0     3  non-null values\n1     3  non-null values\n2     3  non-null values\n3     3  non-null values\n4     3  non-null values\n5     3  non-null values\n6     3  non-null values\n7     3  non-null values\n8     3  non-null values\n9     3  non-null values\n10    3  non-null values\n11    3  non-null values\ndtypes: float64(12)<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"dataframe-column-attribute-access-and-ipython-completion\">\n<h3>DataFrame column attribute access and IPython completion<\/h3>\n<p>If a DataFrame column label is a valid Python variable name, the column can be accessed like attributes:<\/p>\n<div>\n<div>\n<pre>In [578]: df = DataFrame({'foo1' : np.random.randn(5),\n   .....:                 'foo2' : np.random.randn(5)})\n   .....:\n\nIn [579]: df\nOut[579]: \n       foo1      foo2\n0  1.146000  0.563700\n1  1.487349  0.967661\n2  0.604603 -1.057909\n3  2.121453  1.375020\n4  0.597701 -0.928797\n\nIn [580]: df.foo1\nOut[580]: \n0    1.146000\n1    1.487349\n2    0.604603\n3    2.121453\n4    0.597701\nName: foo1, dtype: float64<\/pre>\n<\/div>\n<\/div>\n<p>The columns are also connected to the\u00a0<a href=\"http:\/\/ipython.org\/\">IPython<\/a>\u00a0completion mechanism so they can be tab-completed:<\/p>\n<div>\n<div>\n<pre>In [5]: df.fo&lt;TAB&gt;\ndf.foo1  df.foo2<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"panel\">\n<h2>Panel<\/h2>\n<p>Panel is a somewhat less-used, but still important container for 3-dimensional data. The term\u00a0<a href=\"http:\/\/en.wikipedia.org\/wiki\/Panel_data\">panel data<\/a>\u00a0is 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:<\/p>\n<blockquote>\n<ul>\n<li><strong>items<\/strong>: axis 0, each item corresponds to a DataFrame contained inside<\/li>\n<li><strong>major_axis<\/strong>: axis 1, it is the\u00a0<strong>index<\/strong>\u00a0(rows) of each of the DataFrames<\/li>\n<li><strong>minor_axis<\/strong>: axis 2, it is the\u00a0<strong>columns<\/strong>\u00a0of each of the DataFrames<\/li>\n<\/ul>\n<\/blockquote>\n<p>Construction of Panels works about like you would expect:<\/p>\n<div id=\"from-3d-ndarray-with-optional-axis-labels\">\n<h3>From 3D ndarray with optional axis labels<\/h3>\n<div>\n<div>\n<pre>In [581]: wp = Panel(randn(2, 5, 4), items=['Item1', 'Item2'],\n   .....:            major_axis=date_range('1\/1\/2000', periods=5),\n   .....:            minor_axis=['A', 'B', 'C', 'D'])\n   .....:\n\nIn [582]: wp\nOut[582]: \n&lt;class 'pandas.core.panel.Panel'&gt;\nDimensions: 2 (items) x 5 (major_axis) x 4 (minor_axis)\nItems axis: Item1 to Item2\nMajor_axis axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00\nMinor_axis axis: A to D<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"from-dict-of-dataframe-objects\">\n<h3>From dict of DataFrame objects<\/h3>\n<div>\n<div>\n<pre>In [583]: data = {'Item1' : DataFrame(randn(4, 3)),\n   .....:         'Item2' : DataFrame(randn(4, 2))}\n   .....:\n\nIn [584]: Panel(data)\nOut[584]: \n&lt;class 'pandas.core.panel.Panel'&gt;\nDimensions: 2 (items) x 4 (major_axis) x 3 (minor_axis)\nItems axis: Item1 to Item2\nMajor_axis axis: 0 to 3\nMinor_axis axis: 0 to 2<\/pre>\n<\/div>\n<\/div>\n<p>Note that the values in the dict need only be\u00a0<strong>convertible to DataFrame<\/strong>. Thus, they can be any of the other valid inputs to DataFrame as per above.<\/p>\n<p>One helpful factory method is\u00a0<tt>Panel.from_dict<\/tt>, which takes a dictionary of DataFrames as above, and the following named parameters:<\/p>\n<table border=\"1\">\n<colgroup>\n<col width=\"17%\" \/>\n<col width=\"17%\" \/>\n<col width=\"67%\" \/><\/colgroup>\n<thead valign=\"bottom\">\n<tr>\n<th>Parameter<\/th>\n<th>Default<\/th>\n<th>Description<\/th>\n<\/tr>\n<\/thead>\n<tbody valign=\"top\">\n<tr>\n<td>intersect<\/td>\n<td><tt>False<\/tt><\/td>\n<td>drops elements whose indices do not align<\/td>\n<\/tr>\n<tr>\n<td>orient<\/td>\n<td><tt>items<\/tt><\/td>\n<td>use\u00a0<tt>minor<\/tt>\u00a0to use DataFrames\u2019 columns as panel items<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>For example, compare to the construction above:<\/p>\n<div>\n<div>\n<pre>In [585]: Panel.from_dict(data, orient='minor')\nOut[585]: \n&lt;class 'pandas.core.panel.Panel'&gt;\nDimensions: 3 (items) x 4 (major_axis) x 2 (minor_axis)\nItems axis: 0 to 2\nMajor_axis axis: 0 to 3\nMinor_axis axis: Item1 to Item2<\/pre>\n<\/div>\n<\/div>\n<p>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\u00a0<tt>dtype=object<\/tt>\u00a0unless you pass\u00a0<tt>orient='minor'<\/tt>:<\/p>\n<div>\n<div>\n<pre>In [586]: df = DataFrame({'a': ['foo', 'bar', 'baz'],\n   .....:                 'b': np.random.randn(3)})\n   .....:\n\nIn [587]: df\nOut[587]: \n     a         b\n0  foo -1.537770\n1  bar  0.555759\n2  baz -2.277282\n\nIn [588]: data = {'item1': df, 'item2': df}\n\nIn [589]: panel = Panel.from_dict(data, orient='minor')\n\nIn [590]: panel['a']\nOut[590]: \n  item1 item2\n0   foo   foo\n1   bar   bar\n2   baz   baz\n\nIn [591]: panel['b']\nOut[591]: \n      item1     item2\n0 -1.537770 -1.537770\n1  0.555759  0.555759\n2 -2.277282 -2.277282\n\nIn [592]: panel['b'].dtypes\nOut[592]: \nitem1    float64\nitem2    float64\ndtype: object<\/pre>\n<\/div>\n<\/div>\n<div>\n<p>Note<\/p>\n<p>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.<\/p>\n<\/div>\n<\/div>\n<div id=\"from-dataframe-using-to-panel-method\">\n<h3>From DataFrame using\u00a0<tt>to_panel<\/tt>\u00a0method<\/h3>\n<p>This method was introduced in v0.7 to replace\u00a0<tt>LongPanel.to_long<\/tt>, and converts a DataFrame with a two-level index to a Panel.<\/p>\n<div>\n<div>\n<pre>In [593]: midx = MultiIndex(levels=[['one', 'two'], ['x','y']], labels=[[1,1,0,0],[1,0,1,0]])\n\nIn [594]: df = DataFrame({'A' : [1, 2, 3, 4], 'B': [5, 6, 7, 8]}, index=midx)\n\nIn [595]: df.to_panel()\nOut[595]: \n&lt;class 'pandas.core.panel.Panel'&gt;\nDimensions: 2 (items) x 2 (major_axis) x 2 (minor_axis)\nItems axis: A to B\nMajor_axis axis: one to two\nMinor_axis axis: x to y<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"item-selection-addition-deletion\">\n<h3>Item selection \/ addition \/ deletion<\/h3>\n<p>Similar to DataFrame functioning as a dict of Series, Panel is like a dict of DataFrames:<\/p>\n<div>\n<div>\n<pre>In [596]: wp['Item1']\nOut[596]: \n                   A         B         C         D\n2000-01-01 -0.308853 -0.681087  0.377953  0.493672\n2000-01-02 -2.461467 -1.553902  2.015523 -1.833722\n2000-01-03  1.771740 -0.670027  0.049307 -0.521493\n2000-01-04 -3.201750  0.792716  0.146111  1.903247\n2000-01-05 -0.747169 -0.309038  0.393876  1.861468\n\nIn [597]: wp['Item3'] = wp['Item1'] \/ wp['Item2']<\/pre>\n<\/div>\n<\/div>\n<p>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.<\/p>\n<\/div>\n<div id=\"id1\">\n<h3>Transposing<\/h3>\n<p>A Panel can be rearranged using its\u00a0<tt>transpose<\/tt>\u00a0method (which does not make a copy by default unless the data are heterogeneous):<\/p>\n<div>\n<div>\n<pre>In [598]: wp.transpose(2, 0, 1)\nOut[598]: \n&lt;class 'pandas.core.panel.Panel'&gt;\nDimensions: 4 (items) x 3 (major_axis) x 5 (minor_axis)\nItems axis: A to D\nMajor_axis axis: Item1 to Item3\nMinor_axis axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"id2\">\n<h3>Indexing \/ Selection<\/h3>\n<table border=\"1\">\n<colgroup>\n<col width=\"50%\" \/>\n<col width=\"33%\" \/>\n<col width=\"17%\" \/><\/colgroup>\n<thead valign=\"bottom\">\n<tr>\n<th>Operation<\/th>\n<th>Syntax<\/th>\n<th>Result<\/th>\n<\/tr>\n<\/thead>\n<tbody valign=\"top\">\n<tr>\n<td>Select item<\/td>\n<td><tt>wp[item]<\/tt><\/td>\n<td>DataFrame<\/td>\n<\/tr>\n<tr>\n<td>Get slice at major_axis label<\/td>\n<td><tt>wp.major_xs(val)<\/tt><\/td>\n<td>DataFrame<\/td>\n<\/tr>\n<tr>\n<td>Get slice at minor_axis label<\/td>\n<td><tt>wp.minor_xs(val)<\/tt><\/td>\n<td>DataFrame<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>For example, using the earlier example data, we could do:<\/p>\n<div>\n<div>\n<pre>In [599]: wp['Item1']\nOut[599]: \n                   A         B         C         D\n2000-01-01 -0.308853 -0.681087  0.377953  0.493672\n2000-01-02 -2.461467 -1.553902  2.015523 -1.833722\n2000-01-03  1.771740 -0.670027  0.049307 -0.521493\n2000-01-04 -3.201750  0.792716  0.146111  1.903247\n2000-01-05 -0.747169 -0.309038  0.393876  1.861468\n\nIn [600]: wp.major_xs(wp.major_axis[2])\nOut[600]: \n      Item1     Item2      Item3\nA  1.771740  0.077849  22.758618\nB -0.670027  0.629498  -1.064382\nC  0.049307 -1.035260  -0.047627\nD -0.521493 -0.438229   1.190000\n\nIn [601]: wp.minor_axis\nOut[601]: Index([A, B, C, D], dtype=object)\n\nIn [602]: wp.minor_xs('C')\nOut[602]: \n               Item1     Item2     Item3\n2000-01-01  0.377953 -2.655452 -0.142331\n2000-01-02  2.015523 -1.184357 -1.701786\n2000-01-03  0.049307 -1.035260 -0.047627\n2000-01-04  0.146111 -1.139050 -0.128275\n2000-01-05  0.393876 -0.649593 -0.606343<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"squeezing\">\n<h3>Squeezing<\/h3>\n<p>Another way to change the dimensionality of an object is to\u00a0<tt>squeeze<\/tt>\u00a0a 1-len object, similar to\u00a0<tt>wp['Item1']<\/tt><\/p>\n<div>\n<div>\n<pre>In [603]: wp.reindex(items=['Item1']).squeeze()\nOut[603]: \n                   A         B         C         D\n2000-01-01 -0.308853 -0.681087  0.377953  0.493672\n2000-01-02 -2.461467 -1.553902  2.015523 -1.833722\n2000-01-03  1.771740 -0.670027  0.049307 -0.521493\n2000-01-04 -3.201750  0.792716  0.146111  1.903247\n2000-01-05 -0.747169 -0.309038  0.393876  1.861468\n\nIn [604]: wp.reindex(items=['Item1'],minor=['B']).squeeze()\nOut[604]: \n2000-01-01   -0.681087\n2000-01-02   -1.553902\n2000-01-03   -0.670027\n2000-01-04    0.792716\n2000-01-05   -0.309038\nFreq: D, Name: B, dtype: float64<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"conversion-to-dataframe\">\n<h3>Conversion to DataFrame<\/h3>\n<p>A Panel can be represented in 2D form as a hierarchically indexed DataFrame. See the section\u00a0<a href=\"http:\/\/pandas.pydata.org\/pandas-docs\/dev\/indexing.html#indexing-hierarchical\"><em>hierarchical indexing<\/em><\/a>\u00a0for more on this. To convert a Panel to a DataFrame, use the<tt>to_frame<\/tt>\u00a0method:<\/p>\n<div>\n<div>\n<pre>In [605]: panel = Panel(np.random.randn(3, 5, 4), items=['one', 'two', 'three'],\n   .....:               major_axis=date_range('1\/1\/2000', periods=5),\n   .....:               minor_axis=['a', 'b', 'c', 'd'])\n   .....:\n\nIn [606]: panel.to_frame()\nOut[606]: \n                       one       two     three\nmajor      minor                              \n2000-01-01 a     -0.390201  0.252462 -1.256860\n           b      1.207122  1.500571  0.563637\n           c      0.178690  1.053202 -2.417312\n           d     -1.004168 -2.338595  0.972827\n2000-01-02 a     -1.377627 -0.374279  0.041293\n           b      0.499281 -2.359958  1.129659\n           c     -1.405256 -1.157886  0.086926\n           d      0.162565 -0.551865 -0.445645\n2000-01-03 a     -0.067785  1.592673 -0.217503\n           b     -1.260006  1.559318 -1.420361\n           c     -1.132896  1.562443 -0.015601\n           d     -2.006481  0.763264 -1.150641\n2000-01-04 a      0.301016  0.162027 -0.798334\n           b      0.059117 -0.902704 -0.557697\n           c      1.138469  1.106010  0.381353\n           d     -2.400634 -0.199234  1.337122\n2000-01-05 a     -0.280853  0.458265 -1.531095\n           b      0.025653  0.491048  1.331458\n           c     -1.386071  0.128594 -0.571329\n           d      0.863937  1.147862 -0.026671<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"panel4d-experimental\">\n<h2>Panel4D (Experimental)<\/h2>\n<p><tt>Panel4D<\/tt>\u00a0is a 4-Dimensional named container very much like a\u00a0<tt>Panel<\/tt>, but having 4 named dimensions. It is intended as a test bed for more N-Dimensional named containers.<\/p>\n<blockquote>\n<ul>\n<li><strong>labels<\/strong>: axis 0, each item corresponds to a Panel contained inside<\/li>\n<li><strong>items<\/strong>: axis 1, each item corresponds to a DataFrame contained inside<\/li>\n<li><strong>major_axis<\/strong>: axis 2, it is the\u00a0<strong>index<\/strong>\u00a0(rows) of each of the DataFrames<\/li>\n<li><strong>minor_axis<\/strong>: axis 3, it is the\u00a0<strong>columns<\/strong>\u00a0of each of the DataFrames<\/li>\n<\/ul>\n<\/blockquote>\n<p><tt>Panel4D<\/tt>\u00a0is a sub-class of\u00a0<tt>Panel<\/tt>, so most methods that work on Panels are applicable to Panel4D. The following methods are disabled:<\/p>\n<blockquote>\n<ul>\n<li><tt>join\u00a0,\u00a0to_frame\u00a0,\u00a0to_excel\u00a0,\u00a0to_sparse\u00a0,\u00a0groupby<\/tt><\/li>\n<\/ul>\n<\/blockquote>\n<p>Construction of Panel4D works in a very similar manner to a\u00a0<tt>Panel<\/tt><\/p>\n<div id=\"from-4d-ndarray-with-optional-axis-labels\">\n<h3>From 4D ndarray with optional axis labels<\/h3>\n<div>\n<div>\n<pre>In [607]: p4d = Panel4D(randn(2, 2, 5, 4),\n   .....:            labels=['Label1','Label2'],\n   .....:            items=['Item1', 'Item2'],\n   .....:            major_axis=date_range('1\/1\/2000', periods=5),\n   .....:            minor_axis=['A', 'B', 'C', 'D'])\n   .....:\n\nIn [608]: p4d\nOut[608]: \n&lt;class 'pandas.core.panelnd.Panel4D'&gt;\nDimensions: 2 (labels) x 2 (items) x 5 (major_axis) x 4 (minor_axis)\nLabels axis: Label1 to Label2\nItems axis: Item1 to Item2\nMajor_axis axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00\nMinor_axis axis: A to D<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"from-dict-of-panel-objects\">\n<h3>From dict of Panel objects<\/h3>\n<div>\n<div>\n<pre>In [609]: data = { 'Label1' : Panel({ 'Item1' : DataFrame(randn(4, 3)) }),\n   .....:          'Label2' : Panel({ 'Item2' : DataFrame(randn(4, 2)) }) }\n   .....:\n\nIn [610]: Panel4D(data)\nOut[610]: \n&lt;class 'pandas.core.panelnd.Panel4D'&gt;\nDimensions: 2 (labels) x 2 (items) x 4 (major_axis) x 3 (minor_axis)\nLabels axis: Label1 to Label2\nItems axis: Item1 to Item2\nMajor_axis axis: 0 to 3\nMinor_axis axis: 0 to 2<\/pre>\n<\/div>\n<\/div>\n<p>Note that the values in the dict need only be\u00a0<strong>convertible to Panels<\/strong>. Thus, they can be any of the other valid inputs to Panel as per above.<\/p>\n<\/div>\n<div id=\"slicing\">\n<h3>Slicing<\/h3>\n<p>Slicing works in a similar manner to a Panel.\u00a0<tt>[]<\/tt>\u00a0slices the first dimension.\u00a0<tt>.ix<\/tt>\u00a0allows you to slice abitrarily and get back lower dimensional objects<\/p>\n<div>\n<div>\n<pre>In [611]: p4d['Label1']\nOut[611]: \n&lt;class 'pandas.core.panel.Panel'&gt;\nDimensions: 2 (items) x 5 (major_axis) x 4 (minor_axis)\nItems axis: Item1 to Item2\nMajor_axis axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00\nMinor_axis axis: A to D<\/pre>\n<\/div>\n<\/div>\n<p>4D -&gt; Panel<\/p>\n<div>\n<div>\n<pre>In [612]: p4d.ix[:,:,:,'A']\nOut[612]: \n&lt;class 'pandas.core.panel.Panel'&gt;\nDimensions: 2 (items) x 2 (major_axis) x 5 (minor_axis)\nItems axis: Label1 to Label2\nMajor_axis axis: Item1 to Item2\nMinor_axis axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00<\/pre>\n<\/div>\n<\/div>\n<p>4D -&gt; DataFrame<\/p>\n<div>\n<div>\n<pre>In [613]: p4d.ix[:,:,0,'A']\nOut[613]: \n         Label1    Label2\nItem1 -1.085663  0.399555\nItem2 -0.685597 -1.624062<\/pre>\n<\/div>\n<\/div>\n<p>4D -&gt; Series<\/p>\n<div>\n<div>\n<pre>In [614]: p4d.ix[:,0,0,'A']\nOut[614]: \nLabel1   -1.085663\nLabel2    0.399555\nName: A, dtype: float64<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"id3\">\n<h3>Transposing<\/h3>\n<p>A Panel4D can be rearranged using its\u00a0<tt>transpose<\/tt>\u00a0method (which does not make a copy by default unless the data are heterogeneous):<\/p>\n<div>\n<div>\n<pre>In [615]: p4d.transpose(3, 2, 1, 0)\nOut[615]: \n&lt;class 'pandas.core.panelnd.Panel4D'&gt;\nDimensions: 4 (labels) x 5 (items) x 2 (major_axis) x 2 (minor_axis)\nLabels axis: A to D\nItems axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00\nMajor_axis axis: Item1 to Item2\nMinor_axis axis: Label1 to Label2<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"panelnd-experimental\">\n<h2>PanelND (Experimental)<\/h2>\n<p>PanelND is a module with a set of factory functions to enable a user to construct N-dimensional named containers like Panel4D, with a custom set of axis labels. Thus a domain-specific container can easily be created.<\/p>\n<p>The following creates a Panel5D. A new panel type object must be sliceable into a lower dimensional object. Here we slice to a Panel4D.<\/p>\n<div>\n<div>\n<pre>In [616]: from pandas.core import panelnd\n\nIn [617]: Panel5D = panelnd.create_nd_panel_factory(\n   .....:     klass_name   = 'Panel5D',\n   .....:     axis_orders  = [ 'cool', 'labels','items','major_axis','minor_axis'],\n   .....:     axis_slices  = { 'labels' : 'labels', 'items' : 'items',\n   .....:                      'major_axis' : 'major_axis', 'minor_axis' : 'minor_axis' },\n   .....:     slicer       = Panel4D,\n   .....:     axis_aliases = { 'major' : 'major_axis', 'minor' : 'minor_axis' },\n   .....:     stat_axis    = 2)\n   .....:\n\nIn [618]: p5d = Panel5D(dict(C1 = p4d))\n\nIn [619]: p5d\nOut[619]: \n&lt;class 'pandas.core.panelnd.Panel5D'&gt;\nDimensions: 1 (cool) x 2 (labels) x 2 (items) x 5 (major_axis) x 4 (minor_axis)\nCool axis: C1 to C1\nLabels axis: Label1 to Label2\nItems axis: Item1 to Item2\nMajor_axis axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00\nMinor_axis axis: A to D\n\n# print a slice of our 5D\nIn [620]: p5d.ix['C1',:,:,0:3,:]\nOut[620]: \n&lt;class 'pandas.core.panelnd.Panel4D'&gt;\nDimensions: 2 (labels) x 2 (items) x 3 (major_axis) x 4 (minor_axis)\nLabels axis: Label1 to Label2\nItems axis: Item1 to Item2\nMajor_axis axis: 2000-01-01 00:00:00 to 2000-01-03 00:00:00\nMinor_axis axis: A to D\n\n# transpose it\nIn [621]: p5d.transpose(1,2,3,4,0)\nOut[621]: \n&lt;class 'pandas.core.panelnd.Panel5D'&gt;\nDimensions: 2 (cool) x 2 (labels) x 5 (items) x 4 (major_axis) x 1 (minor_axis)\nCool axis: Label1 to Label2\nLabels axis: Item1 to Item2\nItems axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00\nMajor_axis axis: A to D\nMinor_axis axis: C1 to C1\n\n# look at the shape &amp; dim\nIn [622]: p5d.shape\nOut[622]: [1, 2, 2, 5, 4]\n\nIn [623]: p5d.ndim\nOut[623]: 5<\/pre>\n<\/div>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>We\u2019ll 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,&hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[19],"tags":[],"class_list":["post-147","post","type-post","status-publish","format-standard","hentry","category-python"],"_links":{"self":[{"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/posts\/147","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/comments?post=147"}],"version-history":[{"count":0,"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/posts\/147\/revisions"}],"wp:attachment":[{"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/media?parent=147"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/categories?post=147"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zhuoyao.net\/index.php\/wp-json\/wp\/v2\/tags?post=147"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}