title: K-means clustering on 3 dimensions with sklearn
body: <p>I'm trying to cluster data using lat/lon as X/Y axes and DaysUntilDueDate as my Z axis. I also want to retain the index column ('PM') so that I can create a schedule later using this clustering analysis. The tutorial I found <a href="https://www.linuxcompute.com/product/python-k-means-data-clustering-finding-best-k/" rel="nofollow noreferrer">here</a> has been wonderful but I don't know if it's taking the Z-axis into account, and my poking around hasn't resulted in anything but errors. I think the essential point in the code is the parameters of the <code>iloc</code> bit of this line:</p>
  
  <pre><code>kmeans_model = KMeans(n_clusters=k, random_state=1).fit(A.iloc[:, :])
  </code></pre>
  
  <p>I tried changing this part to <code>iloc[1:4]</code> (to only work on columns 1-3) but that resulted in the following error:</p>
  
  <pre class="lang-none prettyprint-override"><code>ValueError: n_samples=3 should be &gt;= n_clusters=4
  </code></pre>
  
  <p>So my question is: How can I set up my code to run clustering analysis on 3-dimensions while retaining the index ('PM') column?</p>
  
  <p>Here's my python file, thanks for your help:</p>
  
  <pre><code>from sklearn.cluster import KMeans
  import csv
  import pandas as pd
  
  # Import csv file with data in following columns:
  #    [PM (index)] [Longitude] [Latitude] [DaysUntilDueDate]
  
  df = pd.read_csv('point_data_test.csv',index_col=['PM'])
  
  numProjects = len(df)
  K = numProjects // 3    # Around three projects can be worked per day
  
  
  print("Number of projects: ", numProjects)
  print("K-clusters: ", K)
  
  for k in range(1, K):
      # Create a kmeans model on our data, using k clusters.
      #   Random_state helps ensure that the algorithm returns the
      #   same results each time.
      kmeans_model = KMeans(n_clusters=k, random_state=1).fit(df.iloc[:, :])
  
      # These are our fitted labels for clusters --
      #   the first cluster has label 0, and the second has label 1.
      labels = kmeans_model.labels_
  
      # Sum of distances of samples to their closest cluster center
      SSE = kmeans_model.inertia_
  
  print("k:",k, " SSE:", SSE)
  
  # Add labels to df
  df['Labels'] = labels
  #print(df)
  
  df.to_csv('test_KMeans_out.csv')
  </code></pre>