Data is often stored in so-called “stacked” or “record” format:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
In [1]: df Out[1]: date variable value 02000-01-03 A 0.469112 12000-01-04 A -0.282863 22000-01-05 A -1.509059 32000-01-03 B -1.135632 42000-01-04 B 1.212112 52000-01-05 B -0.173215 62000-01-03 C 0.119209 72000-01-04 C -1.044236 82000-01-05 C -0.861849 92000-01-03 D -2.104569 102000-01-04 D -0.494929 112000-01-05 D 1.071804
For the curious here is how the above DataFrame was created:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import pandas.util.testing as tm
tm.N = 3
defunpivot(frame): N, K = frame.shape data = {'value': frame.to_numpy().ravel('F'), 'variable': np.asarray(frame.columns).repeat(N), 'date': np.tile(np.asarray(frame.index), K)} return pd.DataFrame(data, columns=['date', 'variable', 'value'])
df = unpivot(tm.makeTimeDataFrame())
To select out everything for variable A we could do:
1 2 3 4 5 6
In [2]: df[df['variable'] == 'A'] Out[2]: date variable value 02000-01-03 A 0.469112 12000-01-04 A -0.282863 22000-01-05 A -1.509059
But suppose we wish to do time series operations with the variables. A better representation would be where the columns are the unique variables and an index of dates identifies individual observations. To reshape the data into this form, we use the DataFrame.pivot() method (also implemented as a top level function pivot()):
1 2 3 4 5 6 7
In [3]: df.pivot(index='date', columns='variable', values='value') Out[3]: variable A B C D date 2000-01-03 0.469112 -1.1356320.119209 -2.104569 2000-01-04 -0.2828631.212112 -1.044236 -0.494929 2000-01-05 -1.509059 -0.173215 -0.8618491.071804
If the values argument is omitted, and the input DataFrame has more than one column of values which are not used as column or index inputs to pivot, then the resulting “pivoted” DataFrame will have hierarchical columns whose topmost level indicates the respective value column:
1 2 3 4 5 6 7 8 9 10 11 12
In [4]: df['value2'] = df['value'] * 2
In [5]: pivoted = df.pivot(index='date', columns='variable')
In [6]: pivoted Out[6]: value value2 variable A B C D A B C D date 2000-01-03 0.469112 -1.1356320.119209 -2.1045690.938225 -2.2712650.238417 -4.209138 2000-01-04 -0.2828631.212112 -1.044236 -0.494929 -0.5657272.424224 -2.088472 -0.989859 2000-01-05 -1.509059 -0.173215 -0.8618491.071804 -3.018117 -0.346429 -1.7236982.143608
You can then select subsets from the pivoted DataFrame:
1 2 3 4 5 6 7
In [7]: pivoted['value2'] Out[7]: variable A B C D date 2000-01-03 0.938225 -2.2712650.238417 -4.209138 2000-01-04 -0.5657272.424224 -2.088472 -0.989859 2000-01-05 -3.018117 -0.346429 -1.7236982.143608
Note that this returns a view on the underlying data in the case where the data are homogeneously-typed.
::: tip Note
pivot() will error with a ValueError: Index contains duplicate entries, cannot reshape if the index/column pair is not unique. In this case, consider using pivot_table() which is a generalization of pivot that can handle duplicate values for one index/column pair.
:::
Reshaping by stacking and unstacking
Closely related to the pivot() method are the related stack() and unstack() methods available on Series and DataFrame. These methods are designed to work together with MultiIndex objects (see the section on hierarchical indexing). Here are essentially what these methods do:
stack: “pivot” a level of the (possibly hierarchical) column labels, returning a DataFrame with an index with a new inner-most level of row labels.
unstack: (inverse operation of stack) “pivot” a level of the (possibly hierarchical) row index to the column axis, producing a reshaped DataFrame with a new inner-most level of column labels.
The clearest way to explain is by example. Let’s take a prior example data set from the hierarchical indexing section:
In [9]: index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
In [10]: df = pd.DataFrame(np.random.randn(8, 2), index=index, columns=['A', 'B'])
In [11]: df2 = df[:4]
In [12]: df2 Out[12]: A B first second bar one 0.721555 -0.706771 two -1.0395750.271860 baz one -0.4249720.567020 two 0.276232 -1.087401
The stack function “compresses” a level in the DataFrame’s columns to produce either:
A Series, in the case of a simple column Index.
A DataFrame, in the case of a MultiIndex in the columns.
If the columns have a MultiIndex, you can choose which level to stack. The stacked level becomes the new lowest level in a MultiIndex on the columns:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
In [13]: stacked = df2.stack()
In [14]: stacked Out[14]: first second bar one A 0.721555 B -0.706771 two A -1.039575 B 0.271860 baz one A -0.424972 B 0.567020 two A 0.276232 B -1.087401 dtype: float64
With a “stacked” DataFrame or Series (having a MultiIndex as the index), the inverse operation of stack is unstack, which by default unstacks the last level:
In [15]: stacked.unstack() Out[15]: A B first second bar one 0.721555 -0.706771 two -1.0395750.271860 baz one -0.4249720.567020 two 0.276232 -1.087401
In [16]: stacked.unstack(1) Out[16]: second one two first bar A 0.721555 -1.039575 B -0.7067710.271860 baz A -0.4249720.276232 B 0.567020 -1.087401
In [17]: stacked.unstack(0) Out[17]: first bar baz second one A 0.721555 -0.424972 B -0.7067710.567020 two A -1.0395750.276232 B 0.271860 -1.087401
If the indexes have names, you can use the level names instead of specifying the level numbers:
1 2 3 4 5 6 7 8
In [18]: stacked.unstack('second') Out[18]: second one two first bar A 0.721555 -1.039575 B -0.7067710.271860 baz A -0.4249720.276232 B 0.567020 -1.087401
Notice that the stack and unstack methods implicitly sort the index levels involved. Hence a call to stack and then unstack, or vice versa, will result in a sorted copy of the original DataFrame or Series:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
In [19]: index = pd.MultiIndex.from_product([[2, 1], ['a', 'b']])
In [20]: df = pd.DataFrame(np.random.randn(4), index=index, columns=['A'])
In [21]: df Out[21]: A 2 a -0.370647 b -1.157892 1 a -1.344312 b 0.844885
In [22]: all(df.unstack().stack() == df.sort_index()) Out[22]: True
The above code will raise a TypeError if the call to sort_index is removed.
Multiple levels
You may also stack or unstack more than one level at a time by passing a list of levels, in which case the end result is as if each level in the list were processed individually.
In [24]: df = pd.DataFrame(np.random.randn(4, 4), columns=columns)
In [25]: df Out[25]: exp A B A B animal cat cat dog dog hair_length long long short short 01.075770 -0.1090501.643563 -1.469388 10.357021 -0.674600 -1.776904 -0.968914 2 -1.2945240.4137380.276662 -0.472035 3 -0.013960 -0.362543 -0.006154 -0.923061
In [26]: df.stack(level=['animal', 'hair_length']) Out[26]: exp A B animal hair_length 0 cat long 1.075770 -0.109050 dog short 1.643563 -1.469388 1 cat long 0.357021 -0.674600 dog short -1.776904 -0.968914 2 cat long -1.2945240.413738 dog short 0.276662 -0.472035 3 cat long -0.013960 -0.362543 dog short -0.006154 -0.923061
The list of levels can contain either level names or level numbers (but not a mixture of the two).
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# df.stack(level=['animal', 'hair_length']) # from above is equivalent to: In [27]: df.stack(level=[1, 2]) Out[27]: exp A B animal hair_length 0 cat long 1.075770 -0.109050 dog short 1.643563 -1.469388 1 cat long 0.357021 -0.674600 dog short -1.776904 -0.968914 2 cat long -1.2945240.413738 dog short 0.276662 -0.472035 3 cat long -0.013960 -0.362543 dog short -0.006154 -0.923061
Missing data
These functions are intelligent about handling missing data and do not expect each subgroup within the hierarchical index to have the same set of labels. They also can handle the index being unsorted (but you can make it sorted by calling sort_index, of course). Here is a more complex example:
In [29]: index = pd.MultiIndex.from_product([('bar', 'baz', 'foo', 'qux'), ....: ('one', 'two')], ....: names=['first', 'second']) ....:
In [30]: df = pd.DataFrame(np.random.randn(8, 4), index=index, columns=columns)
In [31]: df2 = df.iloc[[0, 1, 2, 4, 5, 7]]
In [32]: df2 Out[32]: exp A B A animal cat dog cat dog first second bar one 0.8957170.805244 -1.2064122.565646 two 1.4312561.340309 -1.170299 -0.226169 baz one 0.4108350.8138500.132003 -0.827317 foo one -1.4136811.6079201.0241800.569605 two 0.875906 -2.2113720.974466 -2.006747 qux two -1.2268250.769804 -1.281247 -0.727707
As mentioned above, stack can be called with a level argument to select which level in the columns to stack:
In [33]: df2.stack('exp') Out[33]: animal cat dog first second exp bar one A 0.8957172.565646 B -1.2064120.805244 two A 1.431256 -0.226169 B -1.1702991.340309 baz one A 0.410835 -0.827317 B 0.1320030.813850 foo one A -1.4136810.569605 B 1.0241801.607920 two A 0.875906 -2.006747 B 0.974466 -2.211372 qux two A -1.226825 -0.727707 B -1.2812470.769804
In [34]: df2.stack('animal') Out[34]: exp A B first second animal bar one cat 0.895717 -1.206412 dog 2.5656460.805244 two cat 1.431256 -1.170299 dog -0.2261691.340309 baz one cat 0.4108350.132003 dog -0.8273170.813850 foo one cat -1.4136811.024180 dog 0.5696051.607920 two cat 0.8759060.974466 dog -2.006747 -2.211372 qux two cat -1.226825 -1.281247 dog -0.7277070.769804
Unstacking can result in missing values if subgroups do not have the same set of labels. By default, missing values will be replaced with the default fill value for that data type, NaN for float, NaT for datetimelike, etc. For integer types, by default data will converted to float and missing values will be set to NaN.
In [36]: df3 Out[36]: exp B animal dog cat first second bar one 0.805244 -1.206412 two 1.340309 -1.170299 foo one 1.6079201.024180 qux two 0.769804 -1.281247
In [37]: df3.unstack() Out[37]: exp B animal dog cat second one two one two first bar 0.8052441.340309 -1.206412 -1.170299 foo 1.607920 NaN 1.024180 NaN qux NaN 0.769804 NaN -1.281247
New in version 0.18.0.
Alternatively, unstack takes an optional fill_value argument, for specifying the value of missing data.
1 2 3 4 5 6 7 8 9
In [38]: df3.unstack(fill_value=-1e9) Out[38]: exp B animal dog cat second one two one two first bar 8.052440e-011.340309e+00 -1.206412e+00 -1.170299e+00 foo 1.607920e+00 -1.000000e+091.024180e+00 -1.000000e+09 qux -1.000000e+097.698036e-01 -1.000000e+09 -1.281247e+00
With a MultiIndex
Unstacking when the columns are a MultiIndex is also careful about doing the right thing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
In [39]: df[:3].unstack(0) Out[39]: exp A B A animal cat dog cat dog first bar baz bar baz bar baz bar baz second one 0.8957170.4108350.8052440.81385 -1.2064120.1320032.565646 -0.827317 two 1.431256 NaN 1.340309 NaN -1.170299 NaN -0.226169 NaN
In [40]: df2.unstack(1) Out[40]: exp A B A animal cat dog cat dog second one two one two one two one two first bar 0.8957171.4312560.8052441.340309 -1.206412 -1.1702992.565646 -0.226169 baz 0.410835 NaN 0.813850 NaN 0.132003 NaN -0.827317 NaN foo -1.4136810.8759061.607920 -2.2113721.0241800.9744660.569605 -2.006747 qux NaN -1.226825 NaN 0.769804 NaN -1.281247 NaN -0.727707
Reshaping by Melt
The top-level melt() function and the corresponding DataFrame.melt() are useful to massage a DataFrame into a format where one or more columns are identifier variables, while all other columns, considered measured variables, are “unpivoted” to the row axis, leaving just two non-identifier columns, “variable” and “value”. The names of those columns can be customized by supplying the var_name and value_name parameters.
In [42]: cheese Out[42]: first last height weight 0 John Doe 5.5130 1 Mary Bo 6.0150
In [43]: cheese.melt(id_vars=['first', 'last']) Out[43]: first last variable value 0 John Doe height 5.5 1 Mary Bo height 6.0 2 John Doe weight 130.0 3 Mary Bo weight 150.0
In [44]: cheese.melt(id_vars=['first', 'last'], var_name='quantity') Out[44]: first last quantity value 0 John Doe height 5.5 1 Mary Bo height 6.0 2 John Doe weight 130.0 3 Mary Bo weight 150.0
Another way to transform is to use the wide_to_long() panel data convenience function. It is less flexible than melt(), but more user-friendly.
In [47]: dft Out[47]: A1970 A1980 B1970 B1980 X id 0 a d 2.53.2 -0.1213060 1 b e 1.21.3 -0.0978831 2 c f 0.70.10.6957752
In [48]: pd.wide_to_long(dft, ["A", "B"], i="id", j="year") Out[48]: X A B id year 01970 -0.121306 a 2.5 11970 -0.097883 b 1.2 219700.695775 c 0.7 01980 -0.121306 d 3.2 11980 -0.097883 e 1.3 219800.695775 f 0.1
Combining with stats and GroupBy
It should be no shock that combining pivot / stack / unstack with GroupBy and the basic Series and DataFrame statistical functions can produce some very expressive and fast data manipulations.
In [49]: df Out[49]: exp A B A animal cat dog cat dog first second bar one 0.8957170.805244 -1.2064122.565646 two 1.4312561.340309 -1.170299 -0.226169 baz one 0.4108350.8138500.132003 -0.827317 two -0.076467 -1.1876781.130127 -1.436737 foo one -1.4136811.6079201.0241800.569605 two 0.875906 -2.2113720.974466 -2.006747 qux one -0.410001 -0.0786380.545952 -1.219217 two -1.2268250.769804 -1.281247 -0.727707
In [50]: df.stack().mean(1).unstack() Out[50]: animal cat dog first second bar one -0.1553471.685445 two 0.1304790.557070 baz one 0.271419 -0.006733 two 0.526830 -1.312207 foo one -0.1947501.088763 two 0.925186 -2.109060 qux one 0.067976 -0.648927 two -1.2540360.021048
# same result, another way In [51]: df.groupby(level=1, axis=1).mean() Out[51]: animal cat dog first second bar one -0.1553471.685445 two 0.1304790.557070 baz one 0.271419 -0.006733 two 0.526830 -1.312207 foo one -0.1947501.088763 two 0.925186 -2.109060 qux one 0.067976 -0.648927 two -1.2540360.021048
In [52]: df.stack().groupby(level=1).mean() Out[52]: exp A B second one 0.0714480.455513 two -0.424186 -0.204486
In [53]: df.mean().unstack(0) Out[53]: exp A B animal cat 0.0608430.018596 dog -0.4135800.232430
Pivot tables
While pivot() provides general purpose pivoting with various data types (strings, numerics, etc.), pandas also provides pivot_table() for pivoting with aggregation of numeric data.
The function pivot_table() can be used to create spreadsheet-style pivot tables. See the cookbook for some advanced strategies.
It takes a number of arguments:
data: a DataFrame object.
values: a column or a list of columns to aggregate.
index: a column, Grouper, array which has the same length as data, or list of them. 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.
columns: a column, Grouper, array which has the same length as data, or list of them. 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.
aggfunc: function to use for aggregation, defaulting to numpy.mean.
In [55]: df = pd.DataFrame({'A': ['one', 'one', 'two', 'three'] * 6, ....: 'B': ['A', 'B', 'C'] * 8, ....: 'C': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 4, ....: 'D': np.random.randn(24), ....: 'E': np.random.randn(24), ....: 'F': [datetime.datetime(2013, i, 1) for i inrange(1, 13)] ....: + [datetime.datetime(2013, i, 15) for i inrange(1, 13)]}) ....:
In [56]: df Out[56]: A B C D E F 0 one A foo 0.341734 -0.3174412013-01-01 1 one B foo 0.959726 -1.2362692013-02-01 2 two C foo -1.1103360.8961712013-03-01 3 three A bar -0.619976 -0.4876022013-04-01 4 one B bar 0.149748 -0.0822402013-05-01 .. ... .. ... ... ... ... 19 three B foo 0.690579 -2.2135882013-08-15 20 one C foo 0.9957611.0633272013-09-15 21 one A bar 2.3967801.2661432013-10-15 22 two B bar 0.0148710.2993682013-11-15 23 three C bar 3.357427 -0.8638382013-12-15
[24 rows x 6 columns]
We can produce pivot tables from this data very easily:
In [57]: pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C']) Out[57]: C bar foo A B one A 1.120915 -0.514058 B -0.3384210.002759 C -0.5388460.699535 three A -1.181568 NaN B NaN 0.433512 C 0.588783 NaN two A NaN 1.000985 B 0.158248 NaN C NaN 0.176180
In [58]: pd.pivot_table(df, values='D', index=['B'], columns=['A', 'C'], aggfunc=np.sum) Out[58]: A one three two C bar foo bar foo bar foo B A 2.241830 -1.028115 -2.363137 NaN NaN 2.001971 B -0.6768430.005518 NaN 0.8670240.316495 NaN C -1.0776921.3990701.177566 NaN NaN 0.352360
In [59]: pd.pivot_table(df, values=['D', 'E'], index=['B'], columns=['A', 'C'], ....: aggfunc=np.sum) ....: Out[59]: D E A one three two one three two C bar foo bar foo bar foo bar foo bar foo bar foo B A 2.241830 -1.028115 -2.363137 NaN NaN 2.0019712.786113 -0.0432111.922577 NaN NaN 0.128491 B -0.6768430.005518 NaN 0.8670240.316495 NaN 1.368280 -1.103384 NaN -2.128743 -0.194294 NaN C -1.0776921.3990701.177566 NaN NaN 0.352360 -1.9768831.495717 -0.263660 NaN NaN 0.872482
The result object is a DataFrame having potentially hierarchical indexes on the rows and columns. If the values column name is not given, the pivot table will include all of the data that can be aggregated in an additional level of hierarchy in the columns:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
In [60]: pd.pivot_table(df, index=['A', 'B'], columns=['C']) Out[60]: D E C bar foo bar foo A B one A 1.120915 -0.5140581.393057 -0.021605 B -0.3384210.0027590.684140 -0.551692 C -0.5388460.699535 -0.9884420.747859 three A -1.181568 NaN 0.961289 NaN B NaN 0.433512 NaN -1.064372 C 0.588783 NaN -0.131830 NaN two A NaN 1.000985 NaN 0.064245 B 0.158248 NaN -0.097147 NaN C NaN 0.176180 NaN 0.436241
In [61]: pd.pivot_table(df, values='D', index=pd.Grouper(freq='M', key='F'), ....: columns='C') ....: Out[61]: C bar foo F 2013-01-31 NaN -0.514058 2013-02-28 NaN 0.002759 2013-03-31 NaN 0.176180 2013-04-30 -1.181568 NaN 2013-05-31 -0.338421 NaN 2013-06-30 -0.538846 NaN 2013-07-31 NaN 1.000985 2013-08-31 NaN 0.433512 2013-09-30 NaN 0.699535 2013-10-311.120915 NaN 2013-11-300.158248 NaN 2013-12-310.588783 NaN
You can render a nice output of the table omitting the missing values by calling to_string if you wish:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
In [62]: table = pd.pivot_table(df, index=['A', 'B'], columns=['C'])
In [63]: print(table.to_string(na_rep='')) D E C bar foo bar foo A B one A 1.120915 -0.5140581.393057 -0.021605 B -0.3384210.0027590.684140 -0.551692 C -0.5388460.699535 -0.9884420.747859 three A -1.1815680.961289 B 0.433512 -1.064372 C 0.588783 -0.131830 two A 1.0009850.064245 B 0.158248 -0.097147 C 0.1761800.436241
Note that pivot_table is also available as an instance method on DataFrame,
Adding margins
If you pass margins=True to pivot_table, special All columns and rows will be added with partial group aggregates across the categories on the rows and columns:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
In [64]: df.pivot_table(index=['A', 'B'], columns='C', margins=True, aggfunc=np.std) Out[64]: D E C bar foo All bar foo All A B one A 1.8043461.2102721.5698790.1794830.4183740.858005 B 0.6903761.3533550.8989981.0838250.9681381.101401 C 0.2736410.4189260.7711391.6892710.4461401.422136 three A 0.794212 NaN 0.7942122.049040 NaN 2.049040 B NaN 0.3635480.363548 NaN 1.6252371.625237 C 3.915454 NaN 3.9154541.035215 NaN 1.035215 two A NaN 0.4429980.442998 NaN 0.4471040.447104 B 0.202765 NaN 0.2027650.560757 NaN 0.560757 C NaN 1.8194081.819408 NaN 0.6504390.650439 All 1.5566860.9525521.2466081.2509240.8999041.059389
Cross tabulations
Use crosstab() to compute a cross-tabulation of two (or more) factors. By default crosstab computes a frequency table of the factors unless an array of values and an aggregation function are passed.
It takes a number of arguments
index: array-like, values to group by in the rows.
columns: array-like, values to group by in the columns.
values: array-like, optional, array of values to aggregate according to the factors.
aggfunc: function, optional, If no values array is passed, computes a frequency table.
rownames: sequence, default None, must match number of row arrays passed.
colnames: sequence, default None, if passed, must match number of column arrays passed.
In [71]: df Out[71]: A B C 0131.0 1231.0 224 NaN 3241.0 4241.0
In [72]: pd.crosstab(df.A, df.B) Out[72]: B 34 A 110 213
Any input passed containing Categorical data will have all of its categories included in the cross-tabulation, even if the actual data does not contain any instances of a particular category.
1 2 3 4 5 6 7 8 9 10
In [73]: foo = pd.Categorical(['a', 'b'], categories=['a', 'b', 'c'])
In [74]: bar = pd.Categorical(['d', 'e'], categories=['d', 'e', 'f'])
In [75]: pd.crosstab(foo, bar) Out[75]: col_0 d e row_0 a 10 b 01
Normalization
New in version 0.18.1.
Frequency tables can also be normalized to show percentages rather than counts using the normalize argument:
1 2 3 4 5 6
In [76]: pd.crosstab(df.A, df.B, normalize=True) Out[76]: B 34 A 10.20.0 20.20.6
normalize can also normalize values within each row or within each column:
1 2 3 4 5 6
In [77]: pd.crosstab(df.A, df.B, normalize='columns') Out[77]: B 34 A 10.50.0 20.51.0
crosstab can also be passed a third Series and an aggregation function (aggfunc) that will be applied to the values of the third Series within each group defined by the first two Series:
1 2 3 4 5 6
In [78]: pd.crosstab(df.A, df.B, values=df.C, aggfunc=np.sum) Out[78]: B 34 A 11.0 NaN 21.02.0
Adding margins
Finally, one can also add margins or normalize this output.
1 2 3 4 5 6 7 8 9
In [79]: pd.crosstab(df.A, df.B, values=df.C, aggfunc=np.sum, normalize=True, ....: margins=True) ....: Out[79]: B 34 All A 10.250.00.25 20.250.50.75 All 0.500.51.00
Tiling
The cut() function computes groupings for the values of the input array and is often used to transform continuous variables to discrete or categorical variables:
If the bins keyword is an IntervalIndex, then these will be used to bin the passed data.:
1
pd.cut([25, 20, 50], bins=c.categories)
Computing indicator / dummy variables
To convert a categorical variable into a “dummy” or “indicator” DataFrame, for example a column in a DataFrame (a Series) which has k distinct values, can derive a DataFrame containing k columns of 1s and 0s using get_dummies():
1 2 3 4 5 6 7 8 9 10 11
In [84]: df = pd.DataFrame({'key': list('bbacab'), 'data1': range(6)})
In [85]: pd.get_dummies(df['key']) Out[85]: a b c 0010 1010 2100 3001 4100 5010
Sometimes it’s useful to prefix the column names, for example when merging the result with the original DataFrame:
get_dummies() also accepts a DataFrame. By default all categorical variables (categorical in the statistical sense, those with object or categorical dtype) are encoded as dummy variables.
In [94]: pd.get_dummies(df) Out[94]: C A_a A_b B_b B_c 011001 120101 231010
All non-object columns are included untouched in the output. You can control the columns that are encoded with the columns keyword.
1 2 3 4 5 6
In [95]: pd.get_dummies(df, columns=['A']) Out[95]: B C A_a A_b 0 c 110 1 c 201 2 b 310
Notice that the B column is still included in the output, it just hasn’t been encoded. You can drop B before calling get_dummies if you don’t want to include it in the output.
As with the Series version, you can pass values for the prefix and prefix_sep. By default the column name is used as the prefix, and ‘_’ as the prefix separator. You can specify prefix and prefix_sep in 3 ways:
string: Use the same value for prefix or prefix_sep for each column to be encoded.
list: Must be the same length as the number of columns being encoded.
In [96]: simple = pd.get_dummies(df, prefix='new_prefix')
In [97]: simple Out[97]: C new_prefix_a new_prefix_b new_prefix_b new_prefix_c 011001 120101 231010
In [98]: from_list = pd.get_dummies(df, prefix=['from_A', 'from_B'])
In [99]: from_list Out[99]: C from_A_a from_A_b from_B_b from_B_c 011001 120101 231010
In [100]: from_dict = pd.get_dummies(df, prefix={'B': 'from_B', 'A': 'from_A'})
In [101]: from_dict Out[101]: C from_A_a from_A_b from_B_b from_B_c 011001 120101 231010
New in version 0.18.0.
Sometimes it will be useful to only keep k-1 levels of a categorical variable to avoid collinearity when feeding the result to statistical models. You can switch to this mode by turn on drop_first.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
In [102]: s = pd.Series(list('abcaa'))
In [103]: pd.get_dummies(s) Out[103]: a b c 0100 1010 2001 3100 4100
In [104]: pd.get_dummies(s, drop_first=True) Out[104]: b c 000 110 201 300 400
When a column contains only one level, it will be omitted in the result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
In [105]: df = pd.DataFrame({'A': list('aaaaa'), 'B': list('ababc')})
If you just want to handle one column as a categorical variable (like R’s factor), you can use df["cat_col"] = pd.Categorical(df["col"]) or df["cat_col"] = df["col"].astype("category"). For full docs on Categorical, see the Categorical introduction and the API documentation.
:::
Examples
In this section, we will review frequently asked questions and examples. The column names and relevant column values are named to correspond with how this DataFrame will be pivoted in the answers below.
Suppose we wanted to pivot df such that the col values are columns, row values are the index, and the mean of val0 are the values? In particular, the resulting DataFrame should look like:
::: tip Note
col col0 col1 col2 col3 col4 row row0 0.77 0.605 NaN 0.860 0.65 row2 0.13 NaN 0.395 0.500 0.25 row3 NaN 0.310 NaN 0.545 NaN row4 NaN 0.100 0.395 0.760 0.24
:::
This solution uses pivot_table(). Also note that aggfunc='mean' is the default. It is included here to be explicit.
1 2 3 4 5 6 7 8 9 10
In [122]: df.pivot_table( .....: values='val0', index='row', columns='col', aggfunc='mean') .....: Out[122]: col col0 col1 col2 col3 col4 row row0 0.770.605 NaN 0.8600.65 row2 0.13 NaN 0.3950.5000.25 row3 NaN 0.310 NaN 0.545 NaN row4 NaN 0.1000.3950.7600.24
Note that we can also replace the missing values by using the fill_value parameter.
Another aggregation we can do is calculate the frequency in which the columns and rows occur together a.k.a. “cross tabulation”. To do this, we can pass size to the aggfunc parameter.
We can also perform multiple aggregations. For example, to perform both a sum and mean, we can pass in a list to the aggfunc argument.
1 2 3 4 5 6 7 8 9 10 11
In [126]: df.pivot_table( .....: values='val0', index='row', columns='col', aggfunc=['mean', 'sum']) .....: Out[126]: mean sum col col0 col1 col2 col3 col4 col0 col1 col2 col3 col4 row row0 0.770.605 NaN 0.8600.650.771.21 NaN 0.860.65 row2 0.13 NaN 0.3950.5000.250.13 NaN 0.790.500.50 row3 NaN 0.310 NaN 0.545 NaN NaN 0.31 NaN 1.09 NaN row4 NaN 0.1000.3950.7600.24 NaN 0.100.791.520.24
Note to aggregate over multiple value columns, we can pass in a list to the values parameter.
1 2 3 4 5 6 7 8 9 10 11 12
In [127]: df.pivot_table( .....: values=['val0', 'val1'], index='row', columns='col', aggfunc=['mean']) .....: Out[127]: mean val0 val1 col col0 col1 col2 col3 col4 col0 col1 col2 col3 col4 row row0 0.770.605 NaN 0.8600.650.010.745 NaN 0.0100.02 row2 0.13 NaN 0.3950.5000.250.45 NaN 0.340.4400.79 row3 NaN 0.310 NaN 0.545 NaN NaN 0.230 NaN 0.075 NaN row4 NaN 0.1000.3950.7600.24 NaN 0.0700.420.3000.46
Note to subdivide over multiple columns we can pass in a list to the columns parameter.
1 2 3 4 5 6 7 8 9 10 11 12 13
In [128]: df.pivot_table( .....: values=['val0'], index='row', columns=['item', 'col'], aggfunc=['mean']) .....: Out[128]: mean val0 item item0 item1 item2 col col2 col3 col4 col0 col1 col2 col3 col4 col0 col1 col3 col4 row row0 NaN NaN NaN 0.77 NaN NaN NaN NaN NaN 0.6050.860.65 row2 0.35 NaN 0.37 NaN NaN 0.44 NaN NaN 0.13 NaN 0.500.13 row3 NaN NaN NaN NaN 0.31 NaN 0.81 NaN NaN NaN 0.28 NaN row4 0.150.64 NaN NaN 0.100.640.880.24 NaN NaN NaN NaN
Exploding a list-like column
New in version 0.25.0.
Sometimes the values in a column are list-like.
1 2 3 4 5 6 7 8 9 10 11 12
In [129]: keys = ['panda1', 'panda2', 'panda3']
In [130]: values = [['eats', 'shoots'], ['shoots', 'leaves'], ['eats', 'leaves']]
In [131]: df = pd.DataFrame({'keys': keys, 'values': values})
We can ‘explode’ the values column, transforming each list-like to a separate row, by using explode(). This will replicate the index values from the original row: