Names must be a list-like
Package:
pandas
30911

Exception Class:
ValueError
Raise code
"""
for all levels). Otherwise level must be None
Raises
------
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")
Links to the raise (1)
https://github.com/pandas-dev/pandas/blob/b3e335254f46a526ee3ce9bb757eac4011d9d1fe/pandas/core/indexes/base.py#L1517Ways to fix
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')
print(df)
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/multi.py in from_arrays(cls, arrays, sortorder, names)
446 sortorder=sortorder,
447 names=names,
--> 448 verify_integrity=False,
449 )
450
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/multi.py 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)
285
286 if sortorder is not None:
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/multi.py 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)
1344
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'))
print(df)
Output:
MultiIndex([(1, 'red'),
(1, 'blue'),
(2, 'red'),
(2, 'blue')],
names=['number', 'color'])
Add a possible fix
Please authorize to post fix