python - 无法使用 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'
解决方案
我认为“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 操作之前,您需要将数据框值转换为列表。
推荐阅读
- angular - Chrome 和 Internet Explorer 的相同场景的不同输出
- nativescript - nativescript 未检测到版本 7
- ios - 在 aws-IOS 设备令牌中出现错误在某些 ios 设备中必须不超过 400 个十六进制字符
- linux - 本地网络上的 WEBRTC,Linux 上没有网关
- google-analytics - Google Analytics - 如何在表格中显示所有主要维度
- c++ - C++ 编译器可以引入 vector.reserve 调用吗?
- python-3.x - Web3 读取合约 Python
- bash - 匹配文件中的文本并在匹配另一个模式的上方打印文本
- html - 为什么ios14以下无法加载网站图片?
- python - 我可以在过滤 numpy 数组方面做得更好吗