2017-10-05 50 views
0

如何在结构化数据中的多列上做k?k表示使用python的结构化数据 - 多于一列

在下面1列(名称)及其所完成的例子

tfidf_matrix = tfidf_vectorizer.fit_transform(df_new [“名”])

这里仅使用名字,但说我们想用的名字和国家,我是否应该将国家添加到同一专栏如下?

df_new['name'] = df_new['name'] + " " + df_new['country'] 
tfidf_matrix = tfidf_vectorizer.fit_transform(df_new['name']) 

它从代码的角度工作,现在还在试图理解的结果(其实我有吨列)的数据,但我不知道这是否是适合当有多个列

正道
import os 
import pandas as pd 
import re 
import numpy as np 

df = pd.read_csv('sample-data.csv') 


def split_description(string): 
    # name 
    string_split = string.split(' - ',1) 
    name = string_split[0] 

    return name 


df_new = pd.DataFrame() 
df_new['name'] = df.loc[:,'description'].apply(lambda x: split_description(x)) 
df_new['id'] = df['id'] 


def remove(name): 
    new_name = re.sub("[0-9]", '', name) 
    new_name = ' '.join(new_name.split()) 
    return new_name 

df_new['name'] = df_new.loc[:,'name'].apply(lambda x: remove(x)) 



from sklearn.feature_extraction.text import TfidfVectorizer 


tfidf_vectorizer = TfidfVectorizer(
            use_idf=True, 
            stop_words = 'english', 
            ngram_range=(1,4), min_df = 0.01, max_df = 0.8) 


tfidf_matrix = tfidf_vectorizer.fit_transform(df_new['name']) 

print (tfidf_matrix.shape) 
print (tfidf_vectorizer.get_feature_names()) 


from sklearn.metrics.pairwise import cosine_similarity 
dist = 1.0 - cosine_similarity(tfidf_matrix) 
print (dist) 


from sklearn.cluster import KMeans 
num_clusters = range(1,20) 

KM = [KMeans(n_clusters=k, random_state = 1).fit(tfidf_matrix) for k in num_clusters] 
+0

KMeans处理二维数据。您是否尝试过在原始数据集上使用Kmeans(没有将它们合并到单个列中),并将它们转换为数字列(如单热编码或二值化) –

+0

thx您的评论,我还没有尝试过,但我有很多专栏,如果我最终使用了30多列,你认为这是一条路吗? (其中一些是描述,编码不起作用) –

+0

对于具有文本的列,tfidf是好的,对于分类列,单热编码将是好的。不管你有多少列,除非你有非常少的数据(行)。如果行数足够大,则这是基本的做法。一旦分析了数据,就可以应用其他高级特征选择和工程技术。 –

回答

0

不,这是适合多列的错误方法。您基本上只是简单地将多个特征卡在一起,并期望它的行为正确,就好像kmeans作为单独的特征应用于这些多列一样。

您需要使用其他方法,如Vectorizo​​r和Pipelines以及tfidifVectorizo​​r在多列上执行此操作。你可以check out this link了解更多信息。

此外,您可以check out this answer为您的问题可能的替代解决方案。