首页 > 解决方案 > 无法使用 numpy 的打印功能和均值功能

问题描述

我正在学习 Udacity 的一门名为 Intro into Data Analysis 的课程,我正在尝试运行此代码,但我一直收到错误消息。我正在使用 Python3。提前致谢。在解释代码和课程的教程视频中,一切正常(我假设是因为它是 Python 的不同版本)。我尝试了很多东西,但我似乎仍然无法使其工作。

%pylab inline

import matplotlib.pyplot as plt
import numpy as np


def describe_data(data):
    print ('Mean:', np.mean(data))
    print ('Standard deviation:', np.std(data))
    print ('Minimum:', np.min(data))
    print ('Maximum:', np.max(data))
    plt.hist(data)
    
describe_data(total_minutes_by_account.values())

这是错误:

Populating the interactive namespace from numpy and matplotlib
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-34-669ffc75246c> in <module>
     14     plt.hist(data)
     15 
---> 16 describe_data(total_minutes_by_account.values())

<ipython-input-34-669ffc75246c> in describe_data(data)
      8 # Summarize the given data
      9 def describe_data(data):
---> 10     print ('Mean:', np.mean(data))
     11     print ('Standard deviation:', np.std(data))
     12     print ('Minimum:', np.min(data))

<__array_function__ internals> in mean(*args, **kwargs)

~\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in mean(a, axis, dtype, out, keepdims, where)
   3417             return mean(axis=axis, dtype=dtype, out=out, **kwargs)
   3418 
-> 3419     return _methods._mean(a, axis=axis, dtype=dtype,
   3420                           out=out, **kwargs)
   3421 

~\Anaconda3\lib\site-packages\numpy\core\_methods.py in _mean(a, axis, dtype, out, keepdims, where)
    188             ret = ret.dtype.type(ret / rcount)
    189     else:
--> 190         ret = ret / rcount
    191 
    192     return ret

TypeError: unsupported operand type(s) for /: 'dict_values' and 'int'

标签: pythonnumpy

解决方案


我认为“total_minutes_by_account”是一个数据框。因此,您可以通过以下方式进行操作。

import matplotlib.pyplot as plt
import numpy as np

def describe_data(data):
    print ('Mean:', np.mean(data))
    print ('Standard deviation:', np.std(data))
    print ('Minimum:', np.min(data))
    print ('Maximum:', np.max(data))
    plt.hist(data)

describe_data(total_minutes_by_account.values.tolist())

在执行任何 numpy 操作之前,您需要将数据框值转换为列表。


推荐阅读