votes up 13

Names must be a list-like

github stars 30911
Exception Class:

Raise code

            for all levels).  Otherwise level must be None

        TypeError if each name is not hashable.
        if not is_list_like(values):
            raise ValueError("Names must be a list-like")
        if len(values) != 1:
            raise ValueError(f"Length of new names must be 1, got {len(values)}")

        # GH 20527
        # All items in 'name' need to be hashable:
        validate_all_hashable(*values, error_name=f"{type(self).__name__}.name")

Ways to fix

votes up 4 votes down

pandas.MultiIndex.from_arrays is used to convert arrays to MultiIndex. It takes the array and the names as a parameter. The names parameter should be given an array like object of strings.

Reproducing the error:

pipenv install pandas

import pandas as pd
import numpy as np
arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']]
df = pd.MultiIndex.from_arrays(arrays, names='number')

The error:

ValueError                                Traceback (most recent call last)
<ipython-input-10-9aae93f15a38> in <module>()
      2 import numpy as np
      3 arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']]
----> 4 df = pd.MultiIndex.from_arrays(arrays, names='number')
      5 print(df)

/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/ in from_arrays(cls, arrays, sortorder, names)
    446             sortorder=sortorder,
    447             names=names,
--> 448             verify_integrity=False,
    449         )

/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/ in __new__(cls, levels, codes, sortorder, names, dtype, copy, name, verify_integrity, _set_identity)
    282         if names is not None:
    283             # handles name validation
--> 284             result._set_names(names)
    286         if sortorder is not None:

/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/ in _set_names(self, names, level, validate)
   1340         # Don't allow a single string for names in a MultiIndex
   1341         if names is not None and not is_list_like(names):
-> 1342             raise ValueError("Names should be list-like for a MultiIndex")
   1343         names = list(names)

ValueError: Names should be list-like for a MultiIndex

Fixed version of the code:

import pandas as pd
import numpy as np
arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']]
df = pd.MultiIndex.from_arrays(arrays, names=('number', 'color'))


MultiIndex([(1,  'red'),
            (1, 'blue'),
            (2,  'red'),
            (2, 'blue')],
           names=['number', 'color'])

Jul 17, 2021 kellemnegasi answer
kellemnegasi 11.7k

Add a possible fix

Please authorize to post fix