租房数据分析,knn算法使用


import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_excel('jiemo.xls') # 导入当前文件夹下的58.csv数据文件 df=pd.DataFrame(data) df1=df.dropna() df1['平方']=df1['平方'].str.replace("㎡","") df1['价格/每平方米']=df1['价格']/df1['平方'].astype(int)

 

d1=df1['地址']
category = pd.Categorical(d1)
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
le.fit(category)
d1=le.transform(d1)

price = df1['价格/每平方米']
adress = d1
plt.scatter(price, adress)
# x,y取值范围设置
# 可以过滤掉一部分脏数据

# 设置title和x,y轴的label
plt.xlabel("price")
plt.ylabel("adress")
plt.show()

 

d1=df1['地址']
category = pd.Categorical(d1)
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
le.fit(category)
d1=le.transform(d1)
print(d1)
d2=df1['朝向']
category = pd.Categorical(d2)
le.fit(category)
d2=le.transform(d2)
print(d2)
d3=df1['类型']
category = pd.Categorical(d3)
le.fit(category)
d3=le.transform(d3)
print(d3)
target=[]
t2=[]
feature=zip(d1,df1['平方'].astype(int),d2,d3)

for i in df1['价格'].astype(int):
    target.append(i)
for i in feature:
    t2.append(i)
[186 163 187 ... 235 231 231]
[31 33 31 ... 33 31 33]
[17 17  5 ... 17  2 39]



from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(t2,target)
knn.score(t2,target)

#0.8762793914246196

knn.predict([[167,80,2,2]])

数据地址:

链接:https://pan.baidu.com/s/1vxt87sgEHFYjCmuyUPPVHg
提取码:eo90
复制这段内容后打开百度网盘手机App,操作更方便哦

上一篇:Numpy和Pandas常用函数速查表


下一篇:pandas之数据选择