title: k-means clustering, Why “KeyError: 0” in the code below:
body: <p>I used this code with my dataset (CSV), but it was originally (Bloops Data) as below:
  &quot;X_train, _ = make_blobs (n_samples = 500, centers = 3, n_features = 2, random_state = 20)&quot;</p>
  <p><strong>the error in</strong> (assign_cluster function &quot;cluster = assign_cluster(k, X, cg_prev)&quot; –)</p>
  <p>And I think that the error occurred for this reason, I hope to get the answer.</p>
  <pre><code>import numpy as np
  import pandas as pd
  from sklearn.datasets import make_blobs
  from matplotlib import pyplot as plt
  from matplotlib.pyplot import figure
  from pandas import DataFrame
  
  X_train= pd.read_csv(&quot;/content/veriseti.csv&quot;)
  
  ##Visualize the data##
  df = DataFrame(dict(x=X_train.iloc[:, 0], y=X_train.iloc[:,1]))
  fig, ax = plt.subplots(figsize=(8,8))
  df.plot(ax=ax, kind='scatter', x='x', y='y')
  plt.xlabel('X_1')
  plt.ylabel('X_2')
  plt.show()
  
  ##functions for K-means
  def init_centroids(k, X):
      arr = []
      for i in range(k):
          cx1 = np.random.uniform(min(X.iloc[:,0]), max(X.iloc[:,0]))
          cx2 = np.random.uniform(min(X.iloc[:,1]), max(X.iloc[:,1]))
          arr.append([cx1, cx2])
      return np.asarray(arr)
  
  def dist(a, b):
      return np.sqrt(sum(np.square(a-b)))
  
  def assign_cluster(k, X, cg):
      cluster = [-1]*len(X)
      for i in range(len(X)):
          dist_arr = []
          for j in range(k):
              dist_arr.append(dist(X[i], cg[j]))
          idx = np.argmin(dist_arr)
          cluster[i] = idx
      return np.asarray(cluster)
  
  def compute_centroids(k, X, cluster):
      cg_arr = []
      for i in range(k):
          arr = []
          for j in range(len(X)):
              if cluster[j]==i:
                  arr.append(X[j])
          cg_arr.append(np.mean(arr, axis=0))
      return np.asarray(cg_arr)
  
  def measure_change(cg_prev, cg_new):
      res = 0
      for a,b in zip(cg_prev,cg_new):
          res+=dist(a,b)
      return res
  
  def show_clusters(X, cluster, cg):
      df = DataFrame(dict(x=X_train.iloc[:, 0], y=X_train.iloc[:, 1], label=cluster))
      colors = {0:'blue', 1:'orange', 2:'green',3:'green',4:'green'}
      fig, ax = plt.subplots(figsize=(8, 8))
      grouped = df.groupby('label')
      for key, group in grouped:
          group.plot(ax=ax, kind='scatter', x='x', y='y', label=key, color=colors[key])
      ax.scatter(cg.iloc[:, 0], cg.iloc[:, 0], marker='*', s=150, c='#ff2222')
      plt.xlabel('x')
      plt.ylabel('y')
      plt.show()
  
  ##K-means
  def k_means(k, X):
      cg_prev = init_centroids(k, X)
      cluster = [0]*len(X)
      cg_change = 100
      while cg_change&gt;.001:
          cluster = assign_cluster(k, X, cg_prev)
          show_clusters(X, cluster, cg_prev)
          cg_new = compute_centroids(k, X, cluster)
          cg_change = measure_change(cg_new, cg_prev)
          cg_prev = cg_new
      return cluster
  
  cluster = k_means(5, X_train)
  </code></pre>
  <p><strong>This is the error message:</strong></p>
  <pre><code>KeyError                                  Traceback (most recent call last)
  /usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
     2894             try:
  -&gt; 2895                 return self._engine.get_loc(casted_key)
     2896             except KeyError as err:
  
  pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
  
  pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
  
  pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
  
  pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
  
  KeyError: 0
  
  The above exception was the direct cause of the following exception:
  
  KeyError                                  Traceback (most recent call last)
  4 frames
  /usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
     2895                 return self._engine.get_loc(casted_key)
     2896             except KeyError as err:
  -&gt; 2897                 raise KeyError(key) from err
     2898 
     2899         if tolerance is not None:
  
  KeyError: 0
  </code></pre>