'DataFrame'对象没有'融化'属性

时间:2017-08-15 18:19:40

标签: python pandas

我只想在pandas中使用融合功能,我只是继续得到同样的错误。

只需输入文档提供的示例:

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

我刚收到错误:

---------------------------------------------------------------------------
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'`

2 个答案:

答案 0 :(得分:12)

您的pandas版本低于0.20.0,因此需要pandas.melt代替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

答案 1 :(得分:2)

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