[英]how to write a matrix to a csv file in python with adding static headers in first row and first column?
I have a matrix which is generated after running a correlation - mat = Statistics.corr(result, method="pearson")
.我有一个在运行相关后生成的矩阵 - mat = Statistics.corr(result, method="pearson")
。 now I want to write this matrix to a csv file but I want to add headers to the first row and first column of the file so that the output looks like this:现在我想将此矩阵写入 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
I have a list which contains the columns names - colmn = ['col1','col2','col3','col4','col5','col6']
.我有一个包含列名称的列表 - colmn = ['col1','col2','col3','col4','col5','col6']
。 The index
in the above format is a static string to indicate the index names.上述格式中的index
是一个静态字符串,用于指示索引名称。 i wrote this code but it only add the header in first row but i am unable to get the header in the first column as well:我写了这段代码,但它只在第一行添加标题,但我也无法在第一列中获取标题:
with open("file1", "wb") as f:
writer = csv.writer(f,delimiter=",")
writer.writerow(['col1','col2','col3','col4','col5','col6'])
writer.writerows(mat)
How can I write the matrix to a csv file with heading static headers to the first row and 1st column?如何将矩阵写入 csv 文件,并将静态标题指向第一行和第一列?
You could use pandas .你可以使用pandas 。 DataFrame.to_csv()
defaults to writing both the column headers and the index. 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')
If on the other hand this is not an option, you can add your index with a little help from enumerate
:另一方面,如果这不是一个选项,您可以在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))
You can use a first variable to indicate the first line, and then add each row name to the row as it is written:您可以使用第一个变量来指示第一行,然后将每行名称添加到所写的行中:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.