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]
KMeans处理二维数据。您是否尝试过在原始数据集上使用Kmeans(没有将它们合并到单个列中),并将它们转换为数字列(如单热编码或二值化) –
thx您的评论,我还没有尝试过,但我有很多专栏,如果我最终使用了30多列,你认为这是一条路吗? (其中一些是描述,编码不起作用) –
对于具有文本的列,tfidf是好的,对于分类列,单热编码将是好的。不管你有多少列,除非你有非常少的数据(行)。如果行数足够大,则这是基本的做法。一旦分析了数据,就可以应用其他高级特征选择和工程技术。 –