【问题标题】:Randomly assign data to clusters within Class Object将数据随机分配给类对象内的集群
【发布时间】:2019-04-16 02:30:12
【问题描述】:

我有以下代码:

import numpy as np

class EM(object):

    # Initialization
    def __init__(self, X, k=2):
       X = np.asarray(X)
       self.data = X.copy()
       # number of clusters
       self.k = k
       # randomly assign data to the clusters
       self.data['label'] = map(lambda x: x + 1, np.random.choice(self.k, len(self.data)))         # gives the error

其中 X 最初是 pd.Dataframe,形状为 (19,182, 5)。运行代码给我以下错误:

IndexError:只有整数、切片 (:)、省略号 (...)、numpy.newaxis (None) 和整数或布尔数组是有效的索引

如何向self.data 写新专栏。这与在类外添加/编写/处理数据对象有何不同?

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    self.data 不再是数据帧,它是一个 numpy 数组。您可以看到这一点,因为您已将 X 转换为带有 np.asarray 的数组。发生 IndexError 是因为您不能像分配数据框那样分配给它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-07
      • 2019-01-09
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多