import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
font = {'family':'SimHei', 'size':'20'}
plt.rc('font', **font)
df = pd.read_csv('data.csv')
df.head()
| CustomerID | Gender | Age | Annual Income (k$) | Spending Score (1-100) |
---|
0 | 1 | Male | 19 | 15 | 39 |
---|
1 | 2 | Male | 21 | 15 | 81 |
---|
2 | 3 | Female | 20 | 16 | 6 |
---|
3 | 4 | Female | 23 | 16 | 77 |
---|
4 | 5 | Female | 31 | 17 | 40 |
---|
df.columns
Index(['CustomerID', 'Gender', 'Age', 'Annual Income (k$)',
'Spending Score (1-100)'],
dtype='object')
df.columns = ['用户ID', '性别', '年龄', '年收入', '支出']
df.head()
| 用户ID | 性别 | 年龄 | 年收入 | 支出 |
---|
0 | 1 | Male | 19 | 15 | 39 |
---|
1 | 2 | Male | 21 | 15 | 81 |
---|
2 | 3 | Female | 20 | 16 | 6 |
---|
3 | 4 | Female | 23 | 16 | 77 |
---|
4 | 5 | Female | 31 | 17 | 40 |
---|
df.isnull().sum()
用户ID 0
性别 0
年龄 0
年收入 0
支出 0
dtype: int64
df.describe()
| 用户ID | 年龄 | 年收入 | 支出 |
---|
count | 200.000000 | 200.000000 | 200.000000 | 200.000000 |
---|
mean | 100.500000 | 38.850000 | 60.560000 | 50.200000 |
---|
std | 57.879185 | 13.969007 | 26.264721 | 25.823522 |
---|
min | 1.000000 | 18.000000 | 15.000000 | 1.000000 |
---|
25% | 50.750000 | 28.750000 | 41.500000 | 34.750000 |
---|
50% | 100.500000 | 36.000000 | 61.500000 | 50.000000 |
---|
75% | 150.250000 | 49.000000 | 78.000000 | 73.000000 |
---|
max | 200.000000 | 70.000000 | 137.000000 | 99.000000 |
---|
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 200 entries, 0 to 199
Data columns (total 5 columns):
用户ID 200 non-null int64
性别 200 non-null object
年龄 200 non-null int64
年收入 200 non-null int64
支出 200 non-null int64
dtypes: int64(4), object(1)
memory usage: 7.9+ KB
查看数据分布
fig = plt.figure(figsize=(20,8))
fig.suptitle('各指标数据分布')
ax1 = fig.add_subplot(221)
ax1.hist(df['年龄'])
ax1.title.set_text('年龄分布')
ax2 = fig.add_subplot(222)
male, female = (df['性别'] == 'Male').sum(), (df['性别'] == 'Female').sum()
height = [male, female]
x = range(len(['男', '女']))
ax2.set_xticks(x)
ax2.set_xticklabels(['男', '女'])
ax2.bar(x, height=height)
ax2.title.set_text('性别比例')
ax3 = fig.add_subplot(223)
ax3.hist(df['年收入'])
ax3.title.set_text('年收入')
ax1 = fig.add_subplot(224)
ax1.hist(df['支出'])
ax1.title.set_text('支出')
fig.subplots_adjust(wspace=0.3,hspace=0.5)
plt.show()
![output_9_0](https://i-blog.csdnimg.cn/blog_migrate/9705f16835bd6e9a1347cd293a2a2159.png#pic_center)
年龄与年收入之间的关系
plt.figure(figsize=(12,6))
for gender in ['Male', 'Female']:
plt.scatter(x='年龄',y='年收入'
,data=df[df['性别']==gender]
,s=200,alpha=0.5,label=gender)
plt.xlabel('年龄')
plt.ylabel('年收入')
plt.title('年龄与年收入之间的关系')
plt.legend()
plt.show()
![output_11_0](https://i-blog.csdnimg.cn/blog_migrate/ed0b4148824b3d6a52b4dc519bab8a9d.png#pic_center)
年龄与支出之间的关系
plt.figure(figsize=(12,6))
for gender in ['Male','Female']:
plt.scatter(x='年龄',y='支出'
,data=df[df['性别']==gender]
,s=200,alpha=0.5,label=gender)
plt.xlabel('年龄')
plt.ylabel('支出')
plt.title('年龄与支出之间的关系')
plt.legend()
plt.show()
![output_13_0](https://i-blog.csdnimg.cn/blog_migrate/8111632de1629e8359bf5a0c3b997b07.png#pic_center)
年收入与支出之间的关系
plt.figure(figsize=(12,6))
for gender in ['Male','Female']:
plt.scatter(x='年收入',y='支出'
,data=df[df['性别']==gender]
,s=200,alpha=0.5,label=gender)
plt.xlabel('年收入')
plt.ylabel('支出')
plt.title('年收入与支出之间的关系')
plt.legend()
plt.show()
![output_15_0](https://i-blog.csdnimg.cn/blog_migrate/94fb60bad059509336b31d97f51af84e.png#pic_center)
年龄与支出的kmeans聚类分析
x1 = df[['年龄', '支出']]
inertia = []
for i in range(1,11):
km = KMeans(n_clusters=i)
km.fit(x1)
inertia.append(km.inertia_)
plt.figure(1,figsize=(12,6))
plt.plot(range(1,11), inertia)
plt.title('查看最佳k值',fontsize=20)
plt.xlabel('簇的数量')
plt.ylabel('簇内误差平方和')
plt.show()
![output_17_0](https://i-blog.csdnimg.cn/blog_migrate/66530346e91021d4e31ad8a616f455ad.png#pic_center)
km = KMeans(n_clusters=4)
y_means = km.fit_predict(x1)
plt.figure(figsize=(12,6))
plt.scatter(x1[y_means==0]['年龄'], x1[y_means==0]['支出'], s= 200,c='salmon')
plt.scatter(x1.iloc[y_means==1,0], x1.iloc[y_means==1,1], s= 200,c='yellowgreen')
plt.scatter(x1.iloc[y_means==2,0], x1.iloc[y_means==2,1], s= 200,c='cornflowerblue')
plt.scatter(x1.iloc[y_means==3,0], x1.iloc[y_means==3,1], s= 200,c='magenta')
plt.scatter(km.cluster_centers_[:,0],km.cluster_centers_[:,1],s=100,c='black',label='中心点')
plt.ylabel('支出')
plt.xlabel('年龄')
plt.legend()
plt.show()
![output_18_0](https://i-blog.csdnimg.cn/blog_migrate/df9b547e185b7993cdaa2097a0cf8ae9.png#pic_center)
年收入与支出的kmeans聚类分析
x2 = df[['年收入','支出']].values
inertia = []
for i in range(1,11):
km = KMeans(n_clusters=i)
km.fit(x2)
inertia.append(km.inertia_)
plt.figure(figsize=(12,6))
plt.plot(range(1,11), inertia)
plt.title('查看最佳k值',fontsize=20)
plt.xlabel('簇的数量')
plt.ylabel('簇内误差平方和')
plt.show()
![output_20_0](https://i-blog.csdnimg.cn/blog_migrate/9b6588093af8a9db22969190ee4414fb.png#pic_center)
km = KMeans(n_clusters=5)
y_means = km.fit_predict(x2)
plt.figure(figsize=(12,6))
plt.scatter(x2[y_means==0,0], x2[y_means==0,1], s= 200,c='salmon')
plt.scatter(x2[y_means==1,0], x2[y_means==1,1], s= 200,c='yellowgreen')
plt.scatter(x2[y_means==2,0], x2[y_means==2,1], s= 200,c='cornflowerblue')
plt.scatter(x2[y_means==3,0], x2[y_means==3,1], s= 200,c='magenta')
plt.scatter(x2[y_means==4,0], x2[y_means==4,1], s= 200,c='LightSeaGreen')
plt.scatter(km.cluster_centers_[:,0],km.cluster_centers_[:,1],s=100,c='black',label='中心点')
plt.ylabel('支出')
plt.xlabel('年收入')
plt.legend()
plt.show()
<matplotlib.figure.Figure at 0x1556354e2b0>
<matplotlib.figure.Figure at 0x155614b37f0>
----------------------------------------------END-------------------------------------