如何在python中将矩阵写入csv文件,并在第一行和第一列中添加静态标题?
我有一个矩阵,它是在运行一个correlation-如何在python中将矩阵写入csv文件,并在第一行和第一列中添加静态标题?,python,csv,matrix,Python,Csv,Matrix,我有一个矩阵,它是在运行一个correlation-mat=Statistics.corr(result,method=“pearson”)之后生成的。现在,我想将此矩阵写入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.0
mat=Statistics.corr(result,method=“pearson”)
之后生成的。现在,我想将此矩阵写入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']
。上述格式中的索引
是一个静态字符串,用于指示索引名称。我编写了这段代码,但它只在第一行中添加了标题,但我也无法在第一列中获取标题:
with open("file1", "wb") as f:
writer = csv.writer(f,delimiter=",")
writer.writerow(['col1','col2','col3','col4','col5','col6'])
writer.writerows(mat)
如何将矩阵写入csv文件,并将标题静态标题写入第一行和第一列?您可以使用。默认为同时写入列标题和索引
import pandas as pd
headers = ['col1','col2','col3','col4','col5','col6']
df = pd.DataFrame(mat, columns=headers, index=headers)
df.to_csv('file1')
另一方面,如果这不是一个选项,您可以在枚举
的帮助下添加索引:
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))
您可以使用第一个变量来指示第一行,然后在写入行时将每行名称添加到该行:
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)
当我使用它时,我发现很少有值是空的。实际上,我的
矩阵
中的一些值是nan
,我认为这就是为什么在编写时它们变为空的原因。我是否可以写入0
以代替在写入时将它们保留为空?将na_rep='0'
传递到到\u csv
。