Q&A
実現したいこと
波形クラスタリングをしたあと、以下の画像のようにクラスタ別に折れ線グラフを作成したいです。
参考にしているもの↓
リンク内容https://tslearn.readthedocs.io/en/stable/auto_examples/clustering/plot_kshape.html#sphx-glr-auto-examples-clustering-plot-kshape-py
実施したこと
<データフレーム>
顧客番号 1 2 3 4 5 6 7 8 9 10 11 12
A 100 200 300 400 500 600 700 800 900 1000 1100 1200
B 8000 7000 5000 4000 3500 3000 2000 1000 700 400 200 100
C 500 900 1200 1500 2000 2300 2600 3000 3400 4700 5600 8000
D 13000 12000 10000 8000 6000 5000 4800 4200 3000 2800 2000 1700
E 8000 10000 12000 13000 13700 20000 21000 24000 29000 31000 34000 70000
F 58000 48000 40000 20000 18000 17000 13000 10000 4800 3000 2400 1200
#クラスター作成 import pandas as pd import numpy as np df = pd.read_csv('K-shape.csv',encoding='shift-jis') df_1 = df.drop('顧客番号',axis=1) from tslearn.clustering import KShape from tslearn.preprocessing import TimeSeriesScalerMeanVariance #標準化 df_2 = TimeSeriesScalerMeanVariance().fit_transform(df_1) ks = KShape(n_clusters=2, verbose=False, random_state=0) y_pred = ks.fit_predict(df_2) df['Cluster'] = y_pred
解決したいグラフ化の部分
import matplotlib.pyplot as plt plt.figure() for i in range(2): plt.subplot(3, 1, 1 + i) for z in df['Cluster' == i]: plt.plot(xx.ravel(), "k-", alpha=.2) plt.plot(ks.cluster_centers_[i].ravel(), "r-") plt.xlim(0, df.shape[1]) plt.ylim(-10, 10) plt.title("Cluster %d" % (i + 1)) plt.tight_layout() plt.show()
エラー
KeyError: False The above exception was the direct cause of the following exception:
補足情報
for z in df['Cluster' == i]: がエラー原因なのかと思い、いろいろ調べたのですが、Cluster数は2つ(0,1)でrangeも(2)にしているので、あっているような気がしており、手詰まりになってしまいました。
あなたの回答
tips
プレビュー