pyspark.pandas.DataFrame.swaplevel

DataFrame.swaplevel(i: Union[int, Any, Tuple[Any, …]] = - 2, j: Union[int, Any, Tuple[Any, …]] = - 1, axis: Union[int, str] = 0) → pyspark.pandas.frame.DataFrame[source]

Swap levels i and j in a MultiIndex on a particular axis.

Parameters
i, jint or str

Levels of the indices to be swapped. Can pass level name as string.

axis{0 or ‘index’, 1 or ‘columns’}, default 0

The axis to swap levels on. 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wise.

Returns
DataFrame

DataFrame with levels swapped in MultiIndex.

Examples

>>> midx = pd.MultiIndex.from_arrays(
...     [['red', 'blue'], [1, 2], ['s', 'm']], names = ['color', 'number', 'size'])
>>> midx  
MultiIndex([( 'red', 1, 's'),
            ('blue', 2, 'm')],
           names=['color', 'number', 'size'])

Swap levels in a MultiIndex on index.

>>> psdf = ps.DataFrame({'x': [5, 6], 'y':[5, 6]}, index=midx)
>>> psdf  
                   x  y
color number size
red   1      s     5  5
blue  2      m     6  6
>>> psdf.swaplevel()  
                   x  y
color size number
red   s    1       5  5
blue  m    2       6  6
>>> psdf.swaplevel(0, 1)  
                   x  y
number color size
1      red   s     5  5
2      blue  m     6  6
>>> psdf.swaplevel('number', 'size')  
                   x  y
color size number
red   s    1       5  5
blue  m    2       6  6

Swap levels in a MultiIndex on columns.

>>> psdf = ps.DataFrame({'x': [5, 6], 'y':[5, 6]})
>>> psdf.columns = midx
>>> psdf
color  red blue
number   1    2
size     s    m
0        5    5
1        6    6
>>> psdf.swaplevel(axis=1)
color  red blue
size     s    m
number   1    2
0        5    5
1        6    6
>>> psdf.swaplevel(axis=1)
color  red blue
size     s    m
number   1    2
0        5    5
1        6    6
>>> psdf.swaplevel(0, 1, axis=1)
number   1    2
color  red blue
size     s    m
0        5    5
1        6    6
>>> psdf.swaplevel('number', 'color', axis=1)
number   1    2
color  red blue
size     s    m
0        5    5
1        6    6