【问题标题】:i am getting an AttributeError我收到一个 AttributeError
【发布时间】:2021-04-23 11:04:14
【问题描述】:

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

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' 对象没有属性 'lstrip'

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

【问题讨论】:

  • 如果代码在晚上停止工作,那么最可能的解释是代码中的某些内容发生了变化。如果您不知道并且没有人可以访问,那么最可能的解释是是您自己忘记了您所做的更改。解决方案是版本控制系统,它可以让您将今天的非工作版本与最新的工作版本进行比较。当您看到更改时,您会记得已应用它。
  • 请解释如果您对一个对象执行.lstrip('distance_from_') 会发生什么,以及为什么您认为x 允许这种使用。

标签: python pandas numpy matplotlib k-means


【解决方案1】:

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

我试过了,效果很好:

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

【讨论】:

  • 当我运行上面的代码时,它第一次运行,但在我运行了几次之后,我开始遇到同样的错误。
  • @Shrivardhana 请检查缩进,运行 4-5 次后我没有收到错误。
  • @Suhas Mucherla 我复制了你的代码并在 jupyter notebook 中运行它,但我仍然得到属性错误
猜你喜欢
  • 2020-03-14
  • 1970-01-01
  • 2017-11-18
  • 2022-01-13
  • 2021-05-24
  • 2018-12-03
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多