Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'DataFrame' object has no attribute 'melt'

Tags:

python

pandas

I just want to use the melt function in pandas and I just keep on getting the same error.

Just typing the example provided by the documentation:

cheese = pd.DataFrame({'first' : ['John', 'Mary'],
                      'last' : ['Doe', 'Bo'],
                       'height' : [5.5, 6.0],
                       'weight' : [130, 150]})

I just get the error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-119-dc0a0b96cf46> in <module>()
----> 1 cheese.melt(id_vars=['first', 'last'])
C:\Anaconda2\lib\site-packages\pandas\core\generic.pyc in __getattr__(self, name)

2670             if name in self._info_axis:
2671                 return self[name]
-> 2672             return object.__getattribute__(self, name)
2673
2674     def __setattr__(self, name, value):

AttributeError: 'DataFrame' object has no attribute 'melt'`
like image 530
Muntram van Chen Avatar asked Aug 15 '17 18:08

Muntram van Chen


People also ask

What does melt () do in Python?

melt() function is useful to message a DataFrame into a format where one or more columns are identifier variables, while all other columns, considered measured variables, are unpivoted to the row axis, leaving just two non-identifier columns, variable and value.

What is DF melt in Python?

DataFrame - melt() function The melt() function is used to unpivot a given DataFrame from wide format to long format, optionally leaving identifier variables set. Syntax: DataFrame.melt(self, id_vars=None, value_vars=None, var_name=None, value_name='value', col_level=None)

How do I index a column in pandas?

In order to set index to column in pandas DataFrame use reset_index() method. By using this you can also set single, multiple indexes to a column. If you are not aware by default, pandas adds an index to each row of the pandas DataFrame.


2 Answers

You pandas version is bellow 0.20.0, so need pandas.melt instead DataFrame.melt:

df = pd.melt(cheese, id_vars=['first', 'last'])
print (df)
  first last variable  value
0  John  Doe   height    5.5
1  Mary   Bo   height    6.0
2  John  Doe   weight  130.0
3  Mary   Bo   weight  150.0
like image 83
jezrael Avatar answered Sep 24 '22 13:09

jezrael


def grilled(d):
    return d.set_index(['first', 'last']) \
            .rename_axis('variable', 1) \
            .stack().reset_index(name='value')

grilled(cheese)

  first last variable  value
0  John  Doe   height    5.5
1  John  Doe   weight  130.0
2  Mary   Bo   height    6.0
3  Mary   Bo   weight  150.0
like image 40
piRSquared Avatar answered Sep 26 '22 13:09

piRSquared