gpt4 book ai didi

python - 如何在 python 中将矩阵写入 csv 文件并在第一行和第一列中添加静态标题?

转载 作者:太空宇宙 更新时间:2023-11-03 16:45:13 25 4
gpt4 key购买 nike

我有一个在运行相关性后生成的矩阵 - 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']。上述格式中的index是一个静态字符串,用于指示索引名称。我编写了这段代码,但它只在第一行中添加标题,但我也无法在第一列中获取标题:

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

如何将矩阵写入 csv 文件,并将静态标题设置为第一行和第一列?

最佳答案

您可以使用pandasDataFrame.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))

关于python - 如何在 python 中将矩阵写入 csv 文件并在第一行和第一列中添加静态标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36377904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com