3

I have a 2D matrix with 13 rows and 13 columns (with headers except for the first column) named correl in Python. This correl matrix was generated from a DataFrame and I wish to populate a matrix correlation with multiple correl. For example:

correlation=[]
correl=df.corr()
correlation=correlation.append(correl) #correlation is not a DataFrame

The reason why I use the correlation=[] it is because I wish to populate the correlation with multiple correlation tables. That is why I use the append since this is in a loop.

Now I wish to export this correlation matrix in a csv file. I do:

with open("C:\destinationfolder\file.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(correlation)

I get this error:

raise KeyError('no item named %s' % com.pprint_thing(item)) KeyError: u'no item named 0'

Why? My guess is that I don't have a header for the first column... is there an easier way to export my correlation table to csv?

Plug4
  • 3,838
  • 9
  • 51
  • 79

1 Answers1

7

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

correlation.to_csv("C:\destinationfolder\file.csv")

Update to answer if you have a list of DataFrames:

If you have a list of DataFrames which you want to make into a csv, you have two options:

  1. concat the list into one larger frame, and use to_csv:

    pd.concat(list_of_dataframes).to_csv(...)
    
  2. iterate over each DataFrame and use to_csv with append (mode='a'). Something like:

    list_of_dataframes[0].to_csv(...)  # write first, using headers..  assumes list isn't empty!
    for df in list_of_dataframes[1:]:
        df.to_csv(..., header=False, mode='a')
    

    see https://stackoverflow.com/a/17531025/1240268.

Community
  • 1
  • 1
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
  • I didn't explain myself correctly in my question. See the changes in my question. I know that correlation is a DataFrame but not if I append each dataframe in a loop. – Plug4 Mar 14 '14 at 18:11
  • @CharlesM in that case you can either: concat to make one big DataFrame and use to_csv, or mode='a' (append) whilst using to_csv. – Andy Hayden Mar 14 '14 at 18:15