Search code examples
pythonnumpypca

Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe' ! astype function between int and float


I want to plot x,y with PCA but i get this problem of casting, despite my list is int and (y,x) are 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)

The error is in the casting :

     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 , ** 

Solution

  • np.choose expects an int array as first argument, but you seem to be passing floats. You can cast the first argument to mitigate this:

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