2016-04-02 6 views
1

私は相関を実行した後に生成される行列を持っています - mat = Statistics.corr(result, method="pearson")。今私は、CSVファイルにこの行列を書きたいが、私は、出力は次のようになりますように、最初の行と、ファイルの最初の列にヘッダを追加したい:最初の行と最初の列に静的ヘッダーを追加して、Pythonでcsvファイルに行列を書き込む方法は?

index,col1,col2,col3,col4,col5,col6 
col1,1,0.005744233,0.013118052,-0.003772589,0.004284689 
col2,0.005744233,1,-0.013269414,-0.007132092,0.013950261 
col3,0.013118052,-0.013269414,1,-0.014029249,-0.00199437 
col4,-0.003772589,-0.007132092,-0.014029249,1,0.022569309 
col5,0.004284689,0.013950261,-0.00199437,0.022569309,1 

私は列を含むリストを持っています名前 - colmn = ['col1','col2','col3','col4','col5','col6']。上記の形式のindexは、インデックス名を示す静的な文字列です。私はこのコードを書いたが、それは最初の行だけにヘッダを追加しますが、私は同様に最初の列のヘッダーを取得することができません:

with open("file1", "wb") as f: 
     writer = csv.writer(f,delimiter=",") 
     writer.writerow(['col1','col2','col3','col4','col5','col6']) 
     writer.writerows(mat) 

私は、静的なヘッダを見出してCSVファイルに行列を書き込むことができますどのように最初の行と1列目?

+0

[numpyの行列に行/列ヘッダーを追加する]の可能な重複(http://stackoverflow.com/questions/11106536/adding-row-column:それが書かれるように行に各列名を追加-headers-to-numpy-matrices) –

答えて

1

pandasを使用できます。 DataFrame.to_csv()の既定値は、列ヘッダーとインデックスの両方を書き込むことです。

import pandas as pd 
headers = ['col1','col2','col3','col4','col5','col6'] 
df = pd.DataFrame(mat, columns=headers, index=headers) 
df.to_csv('file1') 

これは、あなたがenumerateから少し助けを借りて、あなたのインデックスを追加することができますオプションではありません一方場合:

with open("file1", "wb") as f: 
    writer = csv.writer(f,delimiter=",") 
    headers = ['col1','col2','col3','col4','col5','col6'] 
    writer.writerow(['index'] + headers) 
    # If your mat is already a python list of lists, you can skip wrapping 
    # the rows with list() 
    writer.writerows(headers[i:i+1] + list(row) for i, row in enumerate(mat)) 
+0

これを使用すると、空の値はほとんどありません。実際、私の 'matrix'の値のいくつかは' nan'です。なぜなら、それらを書く時に空が空になっている理由です。書き込み中に空のままにする代わりに '0'を書くことは可能でしょうか? – user2966197

+0

'to_csv'に' na_rep = '0'を渡します。 –

0

あなたが最初の行を示すために、最初の変数を使用することができ、かつ

cols = ["col2", "col2", "col3", "col4", "col5"] 

with open("file1", "wb") as f: 
    writer = csv.writer(f) 
    first = True 
    for i, line in enumerate(mat): 
     if first: 
      writer.writerow(["Index"] + cols) 
      first = False 
     else: 
      writer.writerow(["Row"+str(i)] + line)