title: KMeans cluster with multiple columns using grouped dataframe?
body: <p>I am currently working on k-means clustering of multiple groups using groupby.</p>
  <p>The data I'm working on looks like this</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th style="text-align: left;">date</th>
  <th>permno</th>
  <th>mom1m</th>
  <th>mom2m</th>
  <th>...</th>
  <th>mom48m</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td style="text-align: left;">2004-01-31</td>
  <td>80000</td>
  <td>0.515</td>
  <td>-0.32</td>
  <td>...</td>
  <td>0.773</td>
  </tr>
  <tr>
  <td style="text-align: left;">2004-02-29</td>
  <td>80000</td>
  <td>0.415</td>
  <td>-0.043</td>
  <td>...</td>
  <td>0.64</td>
  </tr>
  <tr>
  <td style="text-align: left;">2004-03-31</td>
  <td>80000</td>
  <td>0.314</td>
  <td>0.045</td>
  <td>...</td>
  <td>0.43</td>
  </tr>
  <tr>
  <td style="text-align: left;">2004-01-30</td>
  <td>80001</td>
  <td>0.643</td>
  <td>-0.234</td>
  <td>...</td>
  <td>0.34</td>
  </tr>
  <tr>
  <td style="text-align: left;">2004-02-29</td>
  <td>80001</td>
  <td>0.646</td>
  <td>-0.456</td>
  <td>...</td>
  <td>0.646</td>
  </tr>
  <tr>
  <td style="text-align: left;">2004-03-31</td>
  <td>80001</td>
  <td>0.876</td>
  <td>-0.044</td>
  <td>...</td>
  <td>0.321</td>
  </tr>
  <tr>
  <td style="text-align: left;">2004-01-31</td>
  <td>80002</td>
  <td>0.453</td>
  <td>0.045</td>
  <td>...</td>
  <td>0.324</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>I will be grouping the dataframe based on the dates and I want to perform k-means clustering starting from the columns <code>mom2m</code> to <code>mom48m</code>.</p>
  <p>I would want to have a separate column that shows the labels as well.</p>
  <p>What I have done until now is to make a function that performs the k-means clustering and use <code>transform</code>.</p>
  <pre><code>def cluster(X, n_clusters):
      features = X[features_to_KMeans]
      k_means = KMeans(n_clusters=n_clusters)
      y = kmeans.fit_predict(features)
      return y
  
  crsp['cluster_id'] = crsp.groupby(&quot;date&quot;).transform(cluster, n_clusters=50)
  </code></pre>