首页 > 解决方案 > 我收到一个 AttributeError

问题描述

当我运行以下代码时出现上述错误,在以下代码中我正在尝试制作集群。请帮我纠正这个错误这个错误。

import pandas as pd 
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline

dataframe = {
'x':[12, 20, 28, 18, 29, 33, 24, 45, 45, 52, 51, 
     52, 55, 53, 55, 61, 64, 69,  72],
'y':[39, 36, 30, 52, 54, 46, 55, 59, 63, 70, 66, 
     63,58, 23, 14, 8, 19, 7, 24]
     }

df = pd.DataFrame(dataframe)
np.random.seed(200)
k = 3

plt.style.use('seaborn')
centroids = {
i+1: [np.random.randint(0, 80),
       np.random.randint(0, 80)]
for i in range(k)
}

b = centroids.keys()
fig = plt.figure(figsize=(5, 5))
plt.scatter(df['x'], df['y'], color='k')
colmap = {1:'r', 2:'g', 3:'b'}
for i in b:
   plt.scatter(*centroids[i], color=colmap[i])
plt.xlim(0, 80)
plt.ylim(0, 80)
plt.show

def assignment(df, centroids):
    for i in b:
        df['distance_from_{}'.format(i)] = (
            np.sqrt(
                (df['x'] - centroids[i][0]) ** 2                 
              + (df['y'] - centroids[i][1]) ** 2 
            )
    )
centroids_distance_cols =['distance_from_{}'.format(i) for i in b]
df['closest'] = df.loc[:, centroids_distance_cols].idxmin(axis=1)
df['closest'] = df['closest'].map(lambda x: int(x.lstrip('distance_from_')))
df['closest'] = df['closest'].map(lambda x: colmap[x])
return df
df = assignment(df, centroids)
df.head()

fig = plt.figure(figsize=(5, 5))
plt.scatter(df['x'],         
df['y'],color=df['closest'], alpha=0.5,edgecolor='k')
for i in b:
    plt.scatter(*centroids[i], 
            color=colmap[i])
plt.xlim(0, 80)
plt.ylim(0, 80)
plt.show

这是完整的错误消息: AttributeError: 'float' object has no attribute 'lstrip'

昨天我尝试运行它时代码有效,但今天我遇到了这个错误

标签: pythonpandasnumpymatplotlibk-means

解决方案


函数定义中的缩进不合适!

我试过了,它奏效了:

import pandas as pd 
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline

dataframe = {
'x':[12, 20, 28, 18, 29, 33, 24, 45, 45, 52, 51, 
     52, 55, 53, 55, 61, 64, 69,  72],
'y':[39, 36, 30, 52, 54, 46, 55, 59, 63, 70, 66, 
     63,58, 23, 14, 8, 19, 7, 24]
     }

df = pd.DataFrame(dataframe)
np.random.seed(200)
k = 3

plt.style.use('seaborn')
centroids = {
i+1: [np.random.randint(0, 80),
       np.random.randint(0, 80)]
for i in range(k)
}

b = centroids.keys()
fig = plt.figure(figsize=(5, 5))
plt.scatter(df['x'], df['y'], color='k')
colmap = {1:'r', 2:'g', 3:'b'}
for i in b:
   plt.scatter(*centroids[i], color=colmap[i])
plt.xlim(0, 80)
plt.ylim(0, 80)
plt.show

def assignment(df, centroids):
    for i in b:
        df['distance_from_{}'.format(i)] = (
            np.sqrt(
                (df['x'] - centroids[i][0]) ** 2                 
              + (df['y'] - centroids[i][1]) ** 2 
            )
    )
    centroids_distance_cols =['distance_from_{}'.format(i) for i in b]
    df['closest'] = df.loc[:, centroids_distance_cols].idxmin(axis=1)
    df['closest'] = df['closest'].map(lambda x: int(x.lstrip('distance_from_')))
    df['closest'] = df['closest'].map(lambda x: colmap[x])
    return df
df = assignment(df, centroids)
df.head()

fig = plt.figure(figsize=(5, 5))
plt.scatter(df['x'],         
df['y'],color=df['closest'], alpha=0.5,edgecolor='k')
for i in b:
    plt.scatter(*centroids[i], 
            color=colmap[i])
plt.xlim(0, 80)
plt.ylim(0, 80)
plt.show

在此处输入图像描述


推荐阅读