首页 > 解决方案 > 输出 numpy.linspace 与 numpy.array

问题描述

我正在使用 matplotlib 创建条形图。为了填充条形信息,我最初使用 numpy.linspace 创建一系列值。我现在正在尝试使用从 mySQLdb 获取的一组信息来填充条形信息。

我的问题是 numpy.linspace 输出数组似乎与从选择查询创建的 numpy.array 不同,我不太明白发生了什么。

这是我的原始代码:

theta = np.linspace(0.0, 2 * np.pi, 20, endpoint=False) #array of indexes for each bar
radii = max_height*np.random.rand(20)    #array of heights/radii for each bar
width = (8*np.pi) / 20   #width of each bar

ax = plt.subplot(111, polar=True)
bars = ax.bar(theta, radii, width=width, bottom=bottom)  #setting each bar value

我正在尝试用下面的代码替换上面的 theta 变量:

sql = "SELECT theta FROM table LIMIT 20"
cursor.execute(sql)
thetaArray = cursor.fetchall()
thetaSQL = np.array(thetaArray)

当我尝试使用 thetaSQL 数组时,出现以下错误:

TypeError: only size-1 arrays can be converted to Python scalars

打印出两个数组会返回两种略有不同的格式:

thetaSQL:
    [[0.        ]
     [0.00314159]
     [0.00628319]
     [0.00942478]
     [0.0125664 ]
     [0.015708  ]
     [0.0188496 ]
     [0.0219911 ]
     [0.0251327 ]
     [0.0282743 ]]
linspace theta:
    [0.         0.62831853 1.25663706 1.88495559 2.51327412 3.14159265
     3.76991118 4.39822972 5.02654825 5.65486678]

我怎样才能使它与 sql 数据一起工作?

标签: pythonarraysnumpymatplotlib

解决方案


正如@hpaulj 在评论中提到的,您的选择是:

thetaSQL = np.array(thetaArray).ravel()
thetaSQL = np.array(thetaArray).squeeze()
thetaSQL = np.array(thetaArray).reshape(-1)
thetaSQL = np.array(thetaArray)[:,0]

它们都将二维数组转换为一维数组。


推荐阅读