votes up 1

'name' must be a list / sequence of column names.

Package:
pandas
github stars 30911
Exception Class:
TypeError

Raise code

""" 
        a c  a  c
        b d  b  d
        """
        from pandas import DataFrame

        if name is not None:
            if not is_list_like(name):
                raise TypeError("'name' must be a list / sequence of column names.")

            if len(name) != len(self.levels):
                raise ValueError(
                    "'name' should have same length as number of levels on index."
                )
            idx_names = name
        else:
😲  Walkingbet is Android app that pays you real bitcoins for a walking. Withdrawable real money bonus is available now, hurry up! 🚶

Ways to fix

votes up 1 votes down

the name parameter which specifies the column names must be a list like object that lists the names of the columns needed.

Sample Code to reproduce the exception:

import pandas as pd
mi = pd.MultiIndex.from_arrays([['a', 'b'], ['c', 'd']])
df = mi.to_frame(name="x,y")
df.head()

The displayed error:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-26-39ec81d75fce> in <module>()  1 import pandas as pd  2 mi = pd.MultiIndex.from_arrays([['a', 'b'], ['c', 'd']]) ----> 3 df = mi.to_frame(name="x,y")  4 df.head() 
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/multi.py in to_frame(self, index, name)  1741 if name is not None:  1742 if not is_list_like(name): -> 1743 raise TypeError("'name' must be a list / sequence of column names.")  1744   1745 if len(name) != len(self.levels): 
TypeError: 'name' must be a list / sequence of column names.

Working (Corrected version of the code:

import pandas as pd
mi = pd.MultiIndex.from_arrays([['a', 'b'], ['c', 'd']])
df = mi.to_frame(name=['x', 'y'])
df.head()

Expected output:

May 05, 2022 kellemnegasi answer
kellemnegasi 31.6k

Add a possible fix

Please authorize to post fix