1
$\begingroup$

I'm interested in exporting a correlation matrix to csv. I've tried using the to.csv functionality, but my matrix is obtained from a function and I get an "object has no attribute 'to_csv'" error. I appreciate any guidance. Code is below.

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm as cm

def correlation_matrix(df):

    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    cmap = cm.get_cmap('jet', 30)
    cax = ax1.imshow(df.corr(), interpolation="nearest", cmap=cmap)
    ax1.grid(True)
    plt.title('Feature Correlation')
    labels = None
    # Add colorbar, and make sure to specify tick locations to match desired ticklabels.
    cbar = fig.colorbar(cax, ticks=[-1.1, -0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6,.8,1])
    plt.show()

correlation_matrix(pd.DataFrame(np.c_[Xs,Y]))
$\endgroup$

1 Answer 1

1
$\begingroup$

Don't use the matrix obtained from your function rather,

It looks like correlation is a DataFrame too, so you can simply use to_csv:

correlation_df(within your function itself).to_csv("C:\destinationfolder\file.csv")
$\endgroup$
2
  • $\begingroup$ Don't understand. Do you mean to not use the correlation function, or to export to csv from within it? $\endgroup$ Apr 9, 2018 at 19:54
  • $\begingroup$ What I mean is when using df.corr() it returns a dataframe itself which can easily be exported to different extensions.. you are using numpy to do the same, that's why a matrix,.also you can directly plot Correlation matrices, there are inbuilt functions to do the same or just use the sns.heatmap.. Let me know if I am not clear again $\endgroup$
    – Aditya
    Apr 10, 2018 at 0:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.