【问题标题】:Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe' ! astype function between int and float无法根据规则 'safe' 将数组数据从 dtype('float64') 转换为 dtype('int64') ! int 和 float 之间的 astype 函数
【发布时间】:2018-12-14 11:51:34
【问题描述】:

我想用 PCA 绘制 x,y 但我遇到了这个转换问题,尽管我的列表是 int 并且 (y,x) 是 float :

    csv = np.genfromtxt ('main_contentieux_IPLSCRS_dataset.csv', 
    delimiter=";")
    y = csv[:,0]
    x = csv[:,1:]


    fig = plt.figure(1, figsize=(8, 6))
    plt.clf()
    ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)

    plt.cla()
    pca = decomposition.PCA(n_components=4)
    pca.fit(x)
    X_fits = pca.transform(x)
    for name, label in [('Aixe en provance', 0), ('Paris', 1), 
      ('Versailles', 2)]:
       ax.text3D(X_fits[y == label, 0].mean(),X_fits[y == label, 
       1].mean()+1.5,X_fits[y == label, 
       2].mean(),name,horizontalalignment='center',bbox=dict(alpha=.8, 
       edgecolor='w', facecolor='w'))

   # Reorder the labels to have colors matching the cluster results

   y = np.choose(y,[0,2,1]).astype(np.float)

错误在于铸造:

     y = np.choose(y,[0,2,1]).astype(np.float)

     y is : <class 'numpy.float64'>  and my list [0,2,1] contain int

     ** x and y contains float values,so the problem is in  the casting  when i  try to use (astype) function !  I want to fix it , ** 

【问题讨论】:

  • @cheersmate y 是:[0. 2. 2. ... 1. 1. 1.] 而我的列表是 [0,2,1] 所以当我施放 ( y = np.choose(y,[0,2,1]).astype(np .float)) 我收到此错误:TypeError: Cannot cast array data from dtype('float64') to dtype('int64') 根据规则'safe'
  • 您应该编辑您的答案以包含相关信息。但是你写的离mcve还很远。请read the information in the help docs.

标签: python numpy pca


【解决方案1】:

np.choose 期望 int 数组作为第一个参数,但您似乎在传递浮点数。您可以强制转换第一个参数来缓解这种情况:

y = np.choose(y.astype(int), [0,2,1]).astype(float)

【讨论】:

    猜你喜欢
    • 2019-02-26
    • 2018-08-15
    • 1970-01-01
    • 2021-01-26
    • 2019-03-11
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多