我正在尝试将Numpy数组平坦化,但平坦化、ravel和hstack都做不到。我需要从数组中创建一个Pandas系列,但我似乎无法让Pandas接受平坦化。
print(type(centroids))
# <class 'numpy.matrix'>
print(centroids.shape)
# (5, 9328)
centroid = centroids[i]
centroid = np.hstack(centroid)
print(centroid)
# [[ 0.98487911 0.7483803 11.80978353 ... 0.97687837 0.21988038
3.33842549]] <-- still enclosed by two brackets
print(centroid.shape)
# (1, 9328)
centroid = pd.Series(centroid, name='value') <-- throws exception: Exception: Data must be 1-dimensional
问题在于 centroid 是一个 np.矩阵,而不是一个数组。你的代码只要把最后一行改成就可以了。
centroid = pd.Series(np.array(centroid).ravel(), name='value')