【发布时间】:2019-03-12 17:27:06
【问题描述】:
我正在尝试count 在特定的分箱区域中scatter points 的数量。当我使用 XY 数据中的单个 row 时,code 有效,但是当我尝试使用 iterate 相同的 script 超过众多 rows 时,TypeError 被返回:
TypeError: only length-1 arrays can be converted to Python scalars
例子:
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
np.random.seed(42)
X = np.random.randint(-80, 80, size=(100, 10))
Y = np.random.randint(0, 120, size=(100, 10))
fig, ax = plt.subplots()
BIN_23_X = 0
ang1 = -60, 60
ang2 = 60, 60
angle = math.degrees(math.acos(2/9.15))
E_xy = 0,60
Halfway = mpl.lines.Line2D((BIN_23_X,BIN_23_X), (0,125), color = 'white', lw = 1.5, alpha = 0.8, zorder = 1)
arc1 = mpl.patches.Arc(ang1, 70, 110, angle = 0, theta2 = angle, theta1 = 360-angle, color = 'white', lw = 2)
arc2 = mpl.patches.Arc(ang2, 70, 110, angle = 0, theta2 = 180+angle, theta1 = 180-angle, color = 'white', lw = 2)
Oval = mpl.patches.Ellipse(E_xy, 160, 130, lw = 3, edgecolor = 'black', color = 'white', alpha = 0.2)
ax.add_line(Halfway)
ax.add_patch(arc1)
ax.add_patch(arc2)
ax.add_patch(Oval)
ov1 = mpl.patches.Ellipse(ang1, 70, 110, alpha=0)
ov2 = mpl.patches.Ellipse(ang2, 70, 110, alpha=0)
ax.add_patch(ov1)
ax.add_patch(ov2)
for px, py in zip(X, Y):
#Error occurs in the line below
in_oval = Oval.contains_point(ax.transData.transform(([px, py])), 0)
in_left = ov1.contains_point(ax.transData.transform(([px, py])), 0)
in_right = ov2.contains_point(ax.transData.transform(([px, py])), 0)
on_left = px < 0
on_right = px > 0
if in_oval:
if in_left:
n_bin = 1
elif in_right:
n_bin = 4
elif on_left:
n_bin = 2
elif on_right:
n_bin = 3
else:
n_bin = -1
else:
n_bin = -1
def bin_counts(xA, yA):
bc = dict()
E = Oval.contains_points(ax.transData.transform(np.array([xA, yA]).T), 0)
E_l = ov1.contains_points(ax.transData.transform(np.array([xA, yA]).T), 0)
E_r = ov2.contains_points(ax.transData.transform(np.array([xA, yA]).T), 0)
L = np.array(xA) < 0
R = np.array(xA) > 0
bc[1] = np.sum(E & E_l)
bc[2] = np.sum(E & L & ~E_l)
bc[3] = np.sum(E & R & ~E_r)
bc[4] = np.sum(E & E_r)
return bc
for xr, yr in zip(X, Y):
print(bin_counts(xr, yr))
此行出现错误
in_oval = Oval.contains_point(ax.transData.transform(([px, py])), 0)
追溯:
Studies/Datasets/codes/untitled4.py", line 73, in <module>
in_oval = Oval.contains_point(ax.transData.transform(([px, py])), 0)
File "/Users/jeremyalexander/anaconda/lib/python3.6/site-packages/matplotlib/patches.py", line 154, in contains_point
radius)
File "/Users/jeremyalexander/anaconda/lib/python3.6/site-packages/matplotlib/path.py", line 493, in contains_point
return _path.point_in_path(point[0], point[1], radius, self, transform)
TypeError: only length-1 arrays can be converted to Python scalars
【问题讨论】:
-
请考虑简化您的代码,以便人们更容易理解并帮助您。
-
@EdgarR.Mondragón,我已经取出了一些绘图代码,但其余的对于问题来说是必不可少的。
-
也许尝试显示 2 个代码块:“有效的代码:...”和“无效的代码:...”
-
您为函数提供的参数之一具有更多它可以接受的值。它需要一个标量或可以转换为标量的东西。查看相关函数调用的需求,并查看输入的类型和形状。
-
你知道什么是回溯吗?或者如何准确地告诉我们错误发生在代码的哪个位置?
标签: python pandas numpy dataframe matplotlib