PageRenderTime 55ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/doc/source/reshaping.rst

http://github.com/pydata/pandas
ReStructuredText | 458 lines | 310 code | 148 blank | 0 comment | 0 complexity | ae73fc6db025b342c7131cb59880128a MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0
  1. .. currentmodule:: pandas
  2. .. _reshaping:
  3. .. ipython:: python
  4. :suppress:
  5. import numpy as np
  6. np.random.seed(123456)
  7. from pandas import *
  8. options.display.max_rows=15
  9. from pandas.core.reshape import *
  10. import pandas.util.testing as tm
  11. randn = np.random.randn
  12. np.set_printoptions(precision=4, suppress=True)
  13. from pandas.tools.tile import *
  14. from pandas.compat import zip
  15. **************************
  16. Reshaping and Pivot Tables
  17. **************************
  18. Reshaping by pivoting DataFrame objects
  19. ---------------------------------------
  20. .. ipython::
  21. :suppress:
  22. In [1]: import pandas.util.testing as tm; tm.N = 3
  23. In [2]: def unpivot(frame):
  24. ...: N, K = frame.shape
  25. ...: data = {'value' : frame.values.ravel('F'),
  26. ...: 'variable' : np.asarray(frame.columns).repeat(N),
  27. ...: 'date' : np.tile(np.asarray(frame.index), K)}
  28. ...: columns = ['date', 'variable', 'value']
  29. ...: return DataFrame(data, columns=columns)
  30. ...:
  31. In [3]: df = unpivot(tm.makeTimeDataFrame())
  32. Data is often stored in CSV files or databases in so-called "stacked" or
  33. "record" format:
  34. .. ipython:: python
  35. df
  36. For the curious here is how the above DataFrame was created:
  37. .. code-block:: python
  38. import pandas.util.testing as tm; tm.N = 3
  39. def unpivot(frame):
  40. N, K = frame.shape
  41. data = {'value' : frame.values.ravel('F'),
  42. 'variable' : np.asarray(frame.columns).repeat(N),
  43. 'date' : np.tile(np.asarray(frame.index), K)}
  44. return DataFrame(data, columns=['date', 'variable', 'value'])
  45. df = unpivot(tm.makeTimeDataFrame())
  46. To select out everything for variable ``A`` we could do:
  47. .. ipython:: python
  48. df[df['variable'] == 'A']
  49. But suppose we wish to do time series operations with the variables. A better
  50. representation would be where the ``columns`` are the unique variables and an
  51. ``index`` of dates identifies individual observations. To reshape the data into
  52. this form, use the ``pivot`` function:
  53. .. ipython:: python
  54. df.pivot(index='date', columns='variable', values='value')
  55. If the ``values`` argument is omitted, and the input DataFrame has more than
  56. one column of values which are not used as column or index inputs to ``pivot``,
  57. then the resulting "pivoted" DataFrame will have :ref:`hierarchical columns
  58. <indexing.hierarchical>` whose topmost level indicates the respective value
  59. column:
  60. .. ipython:: python
  61. df['value2'] = df['value'] * 2
  62. pivoted = df.pivot('date', 'variable')
  63. pivoted
  64. You of course can then select subsets from the pivoted DataFrame:
  65. .. ipython:: python
  66. pivoted['value2']
  67. Note that this returns a view on the underlying data in the case where the data
  68. are homogeneously-typed.
  69. .. _reshaping.stacking:
  70. Reshaping by stacking and unstacking
  71. ------------------------------------
  72. Closely related to the ``pivot`` function are the related ``stack`` and
  73. ``unstack`` functions currently available on Series and DataFrame. These
  74. functions are designed to work together with ``MultiIndex`` objects (see the
  75. section on :ref:`hierarchical indexing <indexing.hierarchical>`). Here are
  76. essentially what these functions do:
  77. - ``stack``: "pivot" a level of the (possibly hierarchical) column labels,
  78. returning a DataFrame with an index with a new inner-most level of row
  79. labels.
  80. - ``unstack``: inverse operation from ``stack``: "pivot" a level of the
  81. (possibly hierarchical) row index to the column axis, producing a reshaped
  82. DataFrame with a new inner-most level of column labels.
  83. The clearest way to explain is by example. Let's take a prior example data set
  84. from the hierarchical indexing section:
  85. .. ipython:: python
  86. tuples = list(zip(*[['bar', 'bar', 'baz', 'baz',
  87. 'foo', 'foo', 'qux', 'qux'],
  88. ['one', 'two', 'one', 'two',
  89. 'one', 'two', 'one', 'two']]))
  90. index = MultiIndex.from_tuples(tuples, names=['first', 'second'])
  91. df = DataFrame(randn(8, 2), index=index, columns=['A', 'B'])
  92. df2 = df[:4]
  93. df2
  94. The ``stack`` function "compresses" a level in the DataFrame's columns to
  95. produce either:
  96. - A Series, in the case of a simple column Index
  97. - A DataFrame, in the case of a ``MultiIndex`` in the columns
  98. If the columns have a ``MultiIndex``, you can choose which level to stack. The
  99. stacked level becomes the new lowest level in a ``MultiIndex`` on the columns:
  100. .. ipython:: python
  101. stacked = df2.stack()
  102. stacked
  103. With a "stacked" DataFrame or Series (having a ``MultiIndex`` as the
  104. ``index``), the inverse operation of ``stack`` is ``unstack``, which by default
  105. unstacks the **last level**:
  106. .. ipython:: python
  107. stacked.unstack()
  108. stacked.unstack(1)
  109. stacked.unstack(0)
  110. .. _reshaping.unstack_by_name:
  111. If the indexes have names, you can use the level names instead of specifying
  112. the level numbers:
  113. .. ipython:: python
  114. stacked.unstack('second')
  115. You may also stack or unstack more than one level at a time by passing a list
  116. of levels, in which case the end result is as if each level in the list were
  117. processed individually.
  118. These functions are intelligent about handling missing data and do not expect
  119. each subgroup within the hierarchical index to have the same set of labels.
  120. They also can handle the index being unsorted (but you can make it sorted by
  121. calling ``sortlevel``, of course). Here is a more complex example:
  122. .. ipython:: python
  123. columns = MultiIndex.from_tuples([('A', 'cat'), ('B', 'dog'),
  124. ('B', 'cat'), ('A', 'dog')],
  125. names=['exp', 'animal'])
  126. df = DataFrame(randn(8, 4), index=index, columns=columns)
  127. df2 = df.ix[[0, 1, 2, 4, 5, 7]]
  128. df2
  129. As mentioned above, ``stack`` can be called with a ``level`` argument to select
  130. which level in the columns to stack:
  131. .. ipython:: python
  132. df2.stack('exp')
  133. df2.stack('animal')
  134. Unstacking when the columns are a ``MultiIndex`` is also careful about doing
  135. the right thing:
  136. .. ipython:: python
  137. df[:3].unstack(0)
  138. df2.unstack(1)
  139. .. _reshaping.melt:
  140. Reshaping by Melt
  141. -----------------
  142. The :func:`~pandas.melt` function is useful to massage a
  143. DataFrame into a format where one or more columns are identifier variables,
  144. while all other columns, considered measured variables, are "unpivoted" to the
  145. row axis, leaving just two non-identifier columns, "variable" and "value". The
  146. names of those columns can be customized by supplying the ``var_name`` and
  147. ``value_name`` parameters.
  148. For instance,
  149. .. ipython:: python
  150. cheese = DataFrame({'first' : ['John', 'Mary'],
  151. 'last' : ['Doe', 'Bo'],
  152. 'height' : [5.5, 6.0],
  153. 'weight' : [130, 150]})
  154. cheese
  155. melt(cheese, id_vars=['first', 'last'])
  156. melt(cheese, id_vars=['first', 'last'], var_name='quantity')
  157. Another way to transform is to use the ``wide_to_long`` panel data convenience function.
  158. .. ipython:: python
  159. dft = pd.DataFrame({"A1970" : {0 : "a", 1 : "b", 2 : "c"},
  160. "A1980" : {0 : "d", 1 : "e", 2 : "f"},
  161. "B1970" : {0 : 2.5, 1 : 1.2, 2 : .7},
  162. "B1980" : {0 : 3.2, 1 : 1.3, 2 : .1},
  163. "X" : dict(zip(range(3), np.random.randn(3)))
  164. })
  165. dft["id"] = dft.index
  166. dft
  167. pd.wide_to_long(dft, ["A", "B"], i="id", j="year")
  168. Combining with stats and GroupBy
  169. --------------------------------
  170. It should be no shock that combining ``pivot`` / ``stack`` / ``unstack`` with
  171. GroupBy and the basic Series and DataFrame statistical functions can produce
  172. some very expressive and fast data manipulations.
  173. .. ipython:: python
  174. df
  175. df.stack().mean(1).unstack()
  176. # same result, another way
  177. df.groupby(level=1, axis=1).mean()
  178. df.stack().groupby(level=1).mean()
  179. df.mean().unstack(0)
  180. Pivot tables and cross-tabulations
  181. ----------------------------------
  182. .. _reshaping.pivot:
  183. The function ``pandas.pivot_table`` can be used to create spreadsheet-style pivot
  184. tables. See the :ref:`cookbook<cookbook.pivot>` for some advanced strategies
  185. It takes a number of arguments
  186. - ``data``: A DataFrame object
  187. - ``values``: a column or a list of columns to aggregate
  188. - ``index``: a column, Grouper, array which has the same length as data, or list of them.
  189. Keys to group by on the pivot table index. If an array is passed, it is being used as the same manner as column values.
  190. - ``columns``: a column, Grouper, array which has the same length as data, or list of them.
  191. Keys to group by on the pivot table column. If an array is passed, it is being used as the same manner as column values.
  192. - ``aggfunc``: function to use for aggregation, defaulting to ``numpy.mean``
  193. Consider a data set like this:
  194. .. ipython:: python
  195. import datetime
  196. df = DataFrame({'A' : ['one', 'one', 'two', 'three'] * 6,
  197. 'B' : ['A', 'B', 'C'] * 8,
  198. 'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 4,
  199. 'D' : np.random.randn(24),
  200. 'E' : np.random.randn(24),
  201. 'F' : [datetime.datetime(2013, i, 1) for i in range(1, 13)] +
  202. [datetime.datetime(2013, i, 15) for i in range(1, 13)]})
  203. df
  204. We can produce pivot tables from this data very easily:
  205. .. ipython:: python
  206. pivot_table(df, values='D', index=['A', 'B'], columns=['C'])
  207. pivot_table(df, values='D', index=['B'], columns=['A', 'C'], aggfunc=np.sum)
  208. pivot_table(df, values=['D','E'], index=['B'], columns=['A', 'C'], aggfunc=np.sum)
  209. The result object is a DataFrame having potentially hierarchical indexes on the
  210. rows and columns. If the ``values`` column name is not given, the pivot table
  211. will include all of the data that can be aggregated in an additional level of
  212. hierarchy in the columns:
  213. .. ipython:: python
  214. pivot_table(df, index=['A', 'B'], columns=['C'])
  215. Also, you can use ``Grouper`` for ``index`` and ``columns`` keywords. For detail of ``Grouper``, see :ref:`Grouping with a Grouper specification <groupby.specify>`.
  216. .. ipython:: python
  217. pivot_table(df, values='D', index=Grouper(freq='M', key='F'), columns='C')
  218. You can render a nice output of the table omitting the missing values by
  219. calling ``to_string`` if you wish:
  220. .. ipython:: python
  221. table = pivot_table(df, index=['A', 'B'], columns=['C'])
  222. print(table.to_string(na_rep=''))
  223. Note that ``pivot_table`` is also available as an instance method on DataFrame.
  224. Cross tabulations
  225. ~~~~~~~~~~~~~~~~~
  226. Use the ``crosstab`` function to compute a cross-tabulation of two (or more)
  227. factors. By default ``crosstab`` computes a frequency table of the factors
  228. unless an array of values and an aggregation function are passed.
  229. It takes a number of arguments
  230. - ``index``: array-like, values to group by in the rows
  231. - ``columns``: array-like, values to group by in the columns
  232. - ``values``: array-like, optional, array of values to aggregate according to
  233. the factors
  234. - ``aggfunc``: function, optional, If no values array is passed, computes a
  235. frequency table
  236. - ``rownames``: sequence, default None, must match number of row arrays passed
  237. - ``colnames``: sequence, default None, if passed, must match number of column
  238. arrays passed
  239. - ``margins``: boolean, default False, Add row/column margins (subtotals)
  240. Any Series passed will have their name attributes used unless row or column
  241. names for the cross-tabulation are specified
  242. For example:
  243. .. ipython:: python
  244. foo, bar, dull, shiny, one, two = 'foo', 'bar', 'dull', 'shiny', 'one', 'two'
  245. a = np.array([foo, foo, bar, bar, foo, foo], dtype=object)
  246. b = np.array([one, one, two, one, two, one], dtype=object)
  247. c = np.array([dull, dull, shiny, dull, dull, shiny], dtype=object)
  248. crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'])
  249. .. _reshaping.pivot.margins:
  250. Adding margins (partial aggregates)
  251. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  252. If you pass ``margins=True`` to ``pivot_table``, special ``All`` columns and
  253. rows will be added with partial group aggregates across the categories on the
  254. rows and columns:
  255. .. ipython:: python
  256. df.pivot_table(index=['A', 'B'], columns='C', margins=True, aggfunc=np.std)
  257. .. _reshaping.tile:
  258. Tiling
  259. ------
  260. .. _reshaping.tile.cut:
  261. The ``cut`` function computes groupings for the values of the input array and
  262. is often used to transform continuous variables to discrete or categorical
  263. variables:
  264. .. ipython:: python
  265. ages = np.array([10, 15, 13, 12, 23, 25, 28, 59, 60])
  266. cut(ages, bins=3)
  267. If the ``bins`` keyword is an integer, then equal-width bins are formed.
  268. Alternatively we can specify custom bin-edges:
  269. .. ipython:: python
  270. cut(ages, bins=[0, 18, 35, 70])
  271. .. _reshaping.dummies:
  272. Computing indicator / dummy variables
  273. -------------------------------------
  274. To convert a categorical variable into a "dummy" or "indicator" DataFrame, for example
  275. a column in a DataFrame (a Series) which has ``k`` distinct values, can derive a DataFrame
  276. containing ``k`` columns of 1s and 0s:
  277. .. ipython:: python
  278. df = DataFrame({'key': list('bbacab'), 'data1': range(6)})
  279. get_dummies(df['key'])
  280. Sometimes it's useful to prefix the column names, for example when merging the result
  281. with the original DataFrame:
  282. .. ipython:: python
  283. dummies = get_dummies(df['key'], prefix='key')
  284. dummies
  285. df[['data1']].join(dummies)
  286. This function is often used along with discretization functions like ``cut``:
  287. .. ipython:: python
  288. values = randn(10)
  289. values
  290. bins = [0, 0.2, 0.4, 0.6, 0.8, 1]
  291. get_dummies(cut(values, bins))
  292. See also :func:`Series.str.get_dummies <pandas.core.strings.StringMethods.get_dummies>`.
  293. Factorizing values
  294. ------------------
  295. To encode 1-d values as an enumerated type use ``factorize``:
  296. .. ipython:: python
  297. x = pd.Series(['A', 'A', np.nan, 'B', 3.14, np.inf])
  298. x
  299. labels, uniques = pd.factorize(x)
  300. labels
  301. uniques
  302. Note that ``factorize`` is similar to ``numpy.unique``, but differs in its
  303. handling of NaN:
  304. .. note::
  305. The following ``numpy.unique`` will fail under Python 3 with a ``TypeError``
  306. because of an ordering bug. See also
  307. `Here <https://github.com/numpy/numpy/issues/641>`__
  308. .. ipython:: python
  309. pd.factorize(x, sort=True)
  310. np.unique(x, return_inverse=True)[::-1]