1
1
.. _advanced :
2
2
3
- .. currentmodule :: pandas
4
-
5
- .. ipython :: python
6
- :suppress:
7
-
8
- import numpy as np
9
- import pandas as pd
10
- np.random.seed(123456 )
11
- np.set_printoptions(precision = 4 , suppress = True )
12
- pd.options.display.max_rows = 15
3
+ {{ header }}
13
4
14
5
******************************
15
6
MultiIndex / Advanced Indexing
@@ -62,8 +53,9 @@ The :class:`MultiIndex` object is the hierarchical analogue of the standard
62
53
can think of ``MultiIndex `` as an array of tuples where each tuple is unique. A
63
54
``MultiIndex `` can be created from a list of arrays (using
64
55
:meth: `MultiIndex.from_arrays `), an array of tuples (using
65
- :meth: `MultiIndex.from_tuples `), or a crossed set of iterables (using
66
- :meth: `MultiIndex.from_product `). The ``Index `` constructor will attempt to return
56
+ :meth: `MultiIndex.from_tuples `), a crossed set of iterables (using
57
+ :meth: `MultiIndex.from_product `), or a :class: `DataFrame ` (using
58
+ :meth: `MultiIndex.from_frame `). The ``Index `` constructor will attempt to return
67
59
a ``MultiIndex `` when it is passed a list of tuples. The following examples
68
60
demonstrate different ways to initialize MultiIndexes.
69
61
@@ -89,6 +81,19 @@ to use the :meth:`MultiIndex.from_product` method:
89
81
iterables = [[' bar' , ' baz' , ' foo' , ' qux' ], [' one' , ' two' ]]
90
82
pd.MultiIndex.from_product(iterables, names = [' first' , ' second' ])
91
83
84
+ You can also construct a ``MultiIndex `` from a ``DataFrame `` directly, using
85
+ the method :meth: `MultiIndex.from_frame `. This is a complementary method to
86
+ :meth: `MultiIndex.to_frame `.
87
+
88
+ .. versionadded :: 0.24.0
89
+
90
+ .. ipython :: python
91
+
92
+ df = pd.DataFrame([[' bar' , ' one' ], [' bar' , ' two' ],
93
+ [' foo' , ' one' ], [' foo' , ' two' ]],
94
+ columns = [' first' , ' second' ])
95
+ pd.MultiIndex.from_frame(df)
96
+
92
97
As a convenience, you can pass a list of arrays directly into ``Series `` or
93
98
``DataFrame `` to construct a ``MultiIndex `` automatically:
94
99
@@ -558,7 +563,8 @@ they need to be sorted. As with any index, you can use :meth:`~DataFrame.sort_in
558
563
559
564
.. ipython :: python
560
565
561
- import random; random.shuffle(tuples)
566
+ import random
567
+ random.shuffle(tuples)
562
568
s = pd.Series(np.random.randn(8 ), index = pd.MultiIndex.from_tuples(tuples))
563
569
s
564
570
s.sort_index()
0 commit comments