larray.Array.set_labels

Array.set_labels(axis=None, labels=None, inplace=False, **kwargs) Array[source]

Replace the labels of one or several axes of the array.

Parameters
axisstring or Axis or dict

Axis for which we want to replace labels, or mapping {axis: changes} where changes can either be the complete list of labels, a mapping {old_label: new_label} or a function to transform labels. If there is no ambiguity (two or more axes have the same labels), axis can be a direct mapping {old_label: new_label}.

labelsint, str, iterable or mapping or function, optional

Integer or list of values usable as the collection of labels for an Axis. If this is mapping, it must be {old_label: new_label}. If it is a function, it must be a function accepting a single argument (a label) and returning a single value. This argument must not be used if axis is a mapping.

inplacebool, optional

Whether to modify the original object or return a new array and leave the original intact. Defaults to False.

**kwargs

axis`=`labels for each axis you want to set labels.

Returns
Array

Array with modified labels.

Warning

Not passing a mapping but the complete list of new labels as the ‘labels’ argument must be done with caution. Make sure that the order of new labels corresponds to the exact same order of previous labels.

Examples

>>> a = ndtest('nat=BE,FO;sex=M,F')
>>> a
nat\sex  M  F
     BE  0  1
     FO  2  3
>>> a.set_labels('sex', ['Men', 'Women'])
nat\sex  Men  Women
     BE    0      1
     FO    2      3

when passing a single string as labels, it will be interpreted to create the list of labels, so that one can use the same syntax than during axis creation.

>>> a.set_labels('sex', 'Men,Women')
nat\sex  Men  Women
     BE    0      1
     FO    2      3

to replace only some labels, one must give a mapping giving the new label for each label to replace

>>> a.set_labels('sex', {'M': 'Men'})
nat\sex  Men  F
     BE    0  1
     FO    2  3

to transform labels by a function, use any function accepting and returning a single argument:

>>> a.set_labels('nat', str.lower)
nat\sex  M  F
     be  0  1
     fo  2  3

to replace labels for several axes at the same time, one should give a mapping giving the new labels for each changed axis

>>> a.set_labels({'sex': 'Men,Women', 'nat': 'Belgian,Foreigner'})
  nat\sex  Men  Women
  Belgian    0      1
Foreigner    2      3

or use keyword arguments

>>> a.set_labels(sex='Men,Women', nat='Belgian,Foreigner')
  nat\sex  Men  Women
  Belgian    0      1
Foreigner    2      3

one can also replace some labels in several axes by giving a mapping of mappings

>>> a.set_labels({'sex': {'M': 'Men'}, 'nat': {'BE': 'Belgian'}})
nat\sex  Men  F
Belgian    0  1
     FO    2  3

when there is no ambiguity (two or more axes have the same labels), it is possible to give a mapping between old and new labels

>>> a.set_labels({'M': 'Men', 'BE': 'Belgian'})
nat\sex  Men  F
Belgian    0  1
     FO    2  3