def cluster(data, code, cluster_qq, n_clusters='auto', max_clusters=7):
    '对态度题进行聚类\n    '
    from sklearn.cluster import KMeans
    from sklearn import metrics
    qq_max = sorted(code, key=(lambda x: int(re.findall('\\d+', x)[0])))[(- 1)]
    new_cluster = 'Q{}'.format((int(re.findall('\\d+', qq_max)[0]) + 1))
    qlist = code[cluster_qq]['qlist']
    X = data[qlist]
    std_t = (min((1.41 / np.sqrt(len(qlist))), 0.4) if (len(qlist) >= 8) else 0.1)
    X = X[(X.T.std() > std_t)]
    index_bk = X.index
    X.fillna(0, inplace=True)
    X1 = X.T
    X1 = ((X1 - X1.mean()) / X1.std())
    X1 = X1.T.as_matrix()
    if (n_clusters == 'auto'):
        silhouette_score = []
        SSE_score = []
        klist = np.arange(2, 15)
        for k in klist:
            est = KMeans(k)
            est.fit(X1)
            tmp = np.sum(((X1 - est.cluster_centers_[est.labels_]) ** 2))
            SSE_score.append(tmp)
            tmp = metrics.silhouette_score(X1, est.labels_)
            silhouette_score.append(tmp)
        '\n        fig = plt.figure(1)\n        ax = fig.add_subplot(111)\n        fig = plt.figure(2)\n        ax.plot(klist,np.array(silhouette_score))\n        ax = fig.add_subplot(111)\n        ax.plot(klist,np.array(SSE_score))\n        '
        ss = np.array(silhouette_score)
        t1 = ([False] + list((ss[1:] > ss[:(- 1)])))
        t2 = (list((ss[:(- 1)] > ss[1:])) + [False])
        k_log = [(t1[i] & t2[i]) for i in range(len(t1))]
        if (True in k_log):
            k = k_log.index(True)
        else:
            k = 1
        k = (k if (k <= (max_clusters - 2)) else (max_clusters - 2))
        k_best = klist[k]
    else:
        k_best = n_clusters
    est = KMeans(k_best)
    est.fit(X1)
    SSE = np.sqrt((np.sum(((X1 - est.cluster_centers_[est.labels_]) ** 2)) / len(X1)))
    silhouette_score = metrics.silhouette_score(X1, est.labels_)
    print('有效样本数:{},特征数：{},最佳分类个数：{} 类'.format(len(X1), len(qlist), k_best))
    print('SSE(样本到所在类的质心的距离)为：{:.2f},轮廊系数为: {:.2f}'.format(SSE, silhouette_score))
    "\n    X_PCA = PCA(2).fit_transform(X1)\n    kwargs = dict(cmap = plt.cm.get_cmap('rainbow', 10),\n                  edgecolor='none', alpha=0.6)\n    labels=pd.Series(est.labels_)\n    plt.figure()\n    plt.scatter(X_PCA[:, 0], X_PCA[:, 1], c=labels, **kwargs)\n    "
    "\n    # 三维立体图\n    fig = plt.figure()\n    ax = fig.add_subplot(111, projection='3d')\n    ax.scatter(X_PCA[:, 0], X_PCA[:, 1],X_PCA[:, 2], c=labels, **kwargs)\n    "
    parameters = {'methods': 'kmeans', 'inertia': est.inertia_, 'SSE': SSE, 'silhouette': silhouette_score, 'n_clusters': k_best, 'n_features': len(qlist), 'n_samples': len(X1), 'qnum': new_cluster, 'data': X1, 'labels': est.labels_}
    data[new_cluster] = pd.Series(est.labels_, index=index_bk)
    code[new_cluster] = {'content': '态度题聚类结果', 'qtype': '单选题', 'qlist': [new_cluster], 'code': dict(zip(range(k_best), ['cluster{}'.format((i + 1)) for i in range(k_best)]))}
    print('结果已经存进数据, 题号为：{}'.format(new_cluster))
    return (data, code, parameters)
    "\n    # 对应分析\n    t=data.groupby([new_cluster])[code[cluster_qq]['qlist']].mean()\n    t.columns=['R{}'.format(i+1) for i in range(len(code[cluster_qq]['qlist']))]\n    t=t.rename(index=code[new_cluster]['code'])\n    ca=prince.CA(t)\n    ca.plot_rows_columns(show_row_labels=True,show_column_labels=True)\n    "
对态度题进行聚类
def cluster(data, code, cluster_qq, n_clusters='auto', max_clusters=7):
    '\n    '
    from sklearn.cluster import KMeans
    from sklearn import metrics
    qq_max = sorted(code, key=(lambda x: int(re.findall('\\d+', x)[0])))[(- 1)]
    new_cluster = 'Q{}'.format((int(re.findall('\\d+', qq_max)[0]) + 1))
    qlist = code[cluster_qq]['qlist']
    X = data[qlist]
    std_t = (min((1.41 / np.sqrt(len(qlist))), 0.4) if (len(qlist) >= 8) else 0.1)
    X = X[(X.T.std() > std_t)]
    index_bk = X.index
    X.fillna(0, inplace=True)
    X1 = X.T
    X1 = ((X1 - X1.mean()) / X1.std())
    X1 = X1.T.as_matrix()
    if (n_clusters == 'auto'):
        silhouette_score = []
        SSE_score = []
        klist = np.arange(2, 15)
        for k in klist:
            est = KMeans(k)
            est.fit(X1)
            tmp = np.sum(((X1 - est.cluster_centers_[est.labels_]) ** 2))
            SSE_score.append(tmp)
            tmp = metrics.silhouette_score(X1, est.labels_)
            silhouette_score.append(tmp)
        '\n        fig = plt.figure(1)\n        ax = fig.add_subplot(111)\n        fig = plt.figure(2)\n        ax.plot(klist,np.array(silhouette_score))\n        ax = fig.add_subplot(111)\n        ax.plot(klist,np.array(SSE_score))\n        '
        ss = np.array(silhouette_score)
        t1 = ([False] + list((ss[1:] > ss[:(- 1)])))
        t2 = (list((ss[:(- 1)] > ss[1:])) + [False])
        k_log = [(t1[i] & t2[i]) for i in range(len(t1))]
        if (True in k_log):
            k = k_log.index(True)
        else:
            k = 1
        k = (k if (k <= (max_clusters - 2)) else (max_clusters - 2))
        k_best = klist[k]
    else:
        k_best = n_clusters
    est = KMeans(k_best)
    est.fit(X1)
    SSE = np.sqrt((np.sum(((X1 - est.cluster_centers_[est.labels_]) ** 2)) / len(X1)))
    silhouette_score = metrics.silhouette_score(X1, est.labels_)
    print('有效样本数:{},特征数：{},最佳分类个数：{} 类'.format(len(X1), len(qlist), k_best))
    print('SSE(样本到所在类的质心的距离)为：{:.2f},轮廊系数为: {:.2f}'.format(SSE, silhouette_score))
    "\n    X_PCA = PCA(2).fit_transform(X1)\n    kwargs = dict(cmap = plt.cm.get_cmap('rainbow', 10),\n                  edgecolor='none', alpha=0.6)\n    labels=pd.Series(est.labels_)\n    plt.figure()\n    plt.scatter(X_PCA[:, 0], X_PCA[:, 1], c=labels, **kwargs)\n    "
    "\n    # 三维立体图\n    fig = plt.figure()\n    ax = fig.add_subplot(111, projection='3d')\n    ax.scatter(X_PCA[:, 0], X_PCA[:, 1],X_PCA[:, 2], c=labels, **kwargs)\n    "
    parameters = {'methods': 'kmeans', 'inertia': est.inertia_, 'SSE': SSE, 'silhouette': silhouette_score, 'n_clusters': k_best, 'n_features': len(qlist), 'n_samples': len(X1), 'qnum': new_cluster, 'data': X1, 'labels': est.labels_}
    data[new_cluster] = pd.Series(est.labels_, index=index_bk)
    code[new_cluster] = {'content': '态度题聚类结果', 'qtype': '单选题', 'qlist': [new_cluster], 'code': dict(zip(range(k_best), ['cluster{}'.format((i + 1)) for i in range(k_best)]))}
    print('结果已经存进数据, 题号为：{}'.format(new_cluster))
    return (data, code, parameters)
    "\n    # 对应分析\n    t=data.groupby([new_cluster])[code[cluster_qq]['qlist']].mean()\n    t.columns=['R{}'.format(i+1) for i in range(len(code[cluster_qq]['qlist']))]\n    t=t.rename(index=code[new_cluster]['code'])\n    ca=prince.CA(t)\n    ca.plot_rows_columns(show_row_labels=True,show_column_labels=True)\n    "