我有个问题,我有一个数据集,包含1200060行和3列。列包含点,我必须为它绘制一个三维图。我使用下面的代码,但我不知道错误在哪里。
fig = plt.figure()
ax = plt.axes(projection="3d")
count = len(data1.index)
z_line = np.linspace(0, count, 1000)
x_line = np.cos(z_line)
y_line = np.sin(z_line)
ax.plot3D(x_line, y_line, z_line, 'gray')
z_points = count * data1[['z']]
x_points = np.cos(z_points) + 0.1 * data1[['x']]
y_points = np.sin(z_points) + 0.1 * data1[['y']]
ax.scatter3D(x_points, y_points, z_points, c=z_points, cmap='hsv')
plt.show()
错误为:
ValueError: shape mismatch: objects cannot be broadcast to a single shape
我也试过这个但没有成功
fig = plt.figure()
ax = plt.axes(projection="3d")
x = np.linspace(len(data1['z'].index), len(data1['y'].index), len(data1['x'].index))
y = np.linspace(len(data1['z'].index), len(data1['y'].index), len(data1['x'].index))
X = data1[['x']]
Y = data1[['y']]
Z = data1[['z']]
fig = plt.figure()
ax = plt.axes(projection="3d")
ax.plot_wireframe(X, Y, Z, color='green')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()
这一次运行,但没有显示任何输出
并使用与第一个相同的错误
fig = plt.figure()
ax = plt.axes(projection="3d")
num_bars = len(data1.index)
x_pos = data1[['x']], num_bars
y_pos = data1[['y']], num_bars
z_pos = data1[['z']], num_bars
x_size = np.ones(num_bars)
y_size = np.ones(num_bars)
z_size = np.ones(num_bars)
ax.bar3d(x_pos, y_pos, z_pos, x_size, y_size, z_size, color='aqua')
plt.show()
错误:ValueError: shape mismatch: objects cannot be broadcast to a single shape
使用data1['z']
而不是data1[['z']]
,或者甚至可以使用data1[['z']].values
。
为什么?因为您希望在此处使用系列或numpy数组,而不是使用DataFrames。
查看以下两者之间的区别:
print(type(data1))
# <class 'pandas.core.frame.DataFrame'>
print(type(data1['x']))
#<class 'pandas.core.series.Series'>
print(type(data1['x'].values))
#<class 'numpy.ndarray'>
print(type(data1[['x']]))
#<class 'pandas.core.frame.DataFrame'>
print(type(data1[['x']].values))
#<class 'numpy.ndarray'>
更准确地说,根本问题是Panda不知道应该如何处理添加两个不同名称的列,如图所示:
a = pd.DataFrame({'x':np.arange(0,5)})
b = pd.DataFrame({'y':np.arange(0,5)})
c = pd.DataFrame({'x':np.arange(0,5)})
print(a+b)
### yields:
# x y
# 0 NaN NaN
# 1 NaN NaN
# 2 NaN NaN
# 3 NaN NaN
# 4 NaN NaN
print(a+c)
### yields:
# x
# 0 0
# 1 2
# 2 4
# 3 6
# 4 8