【问题标题】:Numpy Matrix not flatteningNumpy 矩阵没有变平
【发布时间】:2020-08-27 10:16:44
【问题描述】:

我正在尝试展平 Numpy 数组,但展平、拉维尔和 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

【问题讨论】:

  • 这能回答你的问题吗? How to make a flat list out of list of lists?
  • pd.Series(centroid[0], name='value')
  • centroid = centroids[i] 就足够了。
  • @KevinWelch 不幸的是,没有,我试过了,但没有用。即使确实如此,我也在寻找一种基于矩阵的方法……而不是一种迭代的方法。不过还是谢谢。

标签: python pandas numpy matrix


【解决方案1】:

问题在于质心是一个 np.matrix,而不是一个数组。如果您只需将最后一行更改为:

centroid = pd.Series(np.array(centroid).ravel(), name='value')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 2020-01-05
    • 1970-01-01
    • 2015-05-31
    相关资源
    最近更新 更多