python - Python ValueError:无法连接零维数组
问题描述
我正在阅读一本名为“掌握 Python 数据分析”的书,但在数据建模练习中遇到了错误。我得到的错误是:
ValueError:无法连接零维数组
我不确定这个错误是什么意思或导致它的原因。
代码如下:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
from pandas import Series, DataFrame
import numpy.random as rnd
import scipy.stats as st
mean = 0
sdev = 1
nvalues = 10
norm_variate = mean * sdev +rnd.randn(nvalues)
print(norm_variate)
for i, v in enumerate(sorted(norm_variate), start = 1):
print(('{0:2d} {1:+.4f}' .format(i,v)))
def plt_cdf(data, plot_range=None, scale_to=None, **kwargs):
num_bins = len(data)
sorted_data = np.array(sorted(data), dtype=np.float64)
data_range = sorted_data[-1] - sorted_data[0]
counts, bin_edges = np.histogram(sorted_data, bins=num_bins)
xvalues = bin_edges[:1]
yvalues = np.cumsum(counts)
if plot_range is None:
xmin = sorted_data[0]
xmax = sorted_data[-1]
else:
xmin, xmax = plot_range
# pad the arrays
xvalues = np.concatenate([xmin, xvalues[0], xvalues, [xmax]])
yvalues = np.concatenate([[0.0, 0.0], yvalues, [yvalues.max()]])
if scale_to is not NONE:
yvalues = yvalues / len(data) * scale_to
plt.axis([xmin, xmax, 0, yvalues.max()])
return plt.plt(xvalues, yvalues, **kwargs)
nvalues = 20
norm_variate = rnd.randn(nvalues)
plt_cdf(norm_variate, plot_range=[-3,3], scale_to=1.0, lw=2.5, color='Brown')
for v in [0.25, 0.5, 0.75]:
plt.axhline(v, lw=1, ls='--', color='black')
任何帮助都感激不尽。
解决方案
制作一个简单的数组和几个标量值:
In [197]: x = np.arange(4)
In [198]: x0=x[0]; x1=x[-1]
尝试加入他们会产生错误:
In [199]: np.concatenate([x0, x, x1])
Traceback (most recent call last):
File "<ipython-input-199-9131e46a3dcd>", line 1, in <module>
np.concatenate([x0, x, x1])
File "<__array_function__ internals>", line 5, in concatenate
ValueError: zero-dimensional arrays cannot be concatenated
但是添加 [] 来定义列表,因此添加 1 个元素数组,可以:
In [200]: np.concatenate([[x0], x, [x1]])
Out[200]: array([0, 0, 1, 2, 3, 3])
hstack
做同样的事情 - 将任何标量转换为数组
In [201]: np.hstack([x0,x,x1])
Out[201]: array([0, 0, 1, 2, 3, 3])
跟踪尺寸是使用numpy
. 不要做假设。尤其是有错误的时候,测试,再测试。
推荐阅读
- android - Android volley 请求获取令牌 400 错误
- c# - Xamarin 在点击时设置 StackLayout 的 BackgroundColor
- unity3d - 为什么 OnMouseDown、Drag、Up 在 unity2d 中不起作用?
- jenkins - Jenkins EnvInject 插件向构建发起者发送邮件
- sapui5 - SAP UI5 使用参数创建视图
- c - 为什么 NtOpenSection 返回错误号 0xc0000024?
- hdfs - 如何从 HDFS 恢复已删除的文件夹
- mysql - Kafka producer vs Kafka connect to read MySQL Datasource
- python - 袖扣(Plotly)箱线图未正确显示异常值
- python - 传单 jupyter 绘图颜色密度热图