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

标签 python csv matrix

我有一个在运行相关性后生成的矩阵 - 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/

相关文章:

python - 在 Conda 环境中安装 Apache-Airflow

php - 使用 PHP 将 MySQL 表转换为 CSV - 没有限制器问题

python - Tensorflow中将数组转换为矩阵,其元素填充矩阵的上三角

r - 如何有效生成对称矩阵的下三角索引

c++ - 如何在 C++ 中使用 2 个循环制作一个完整的矩阵

Python:如何获取当前命名空间中所有对象的大小?

c++ - 糟糕 : the __cmp__ function

java - 导出 CSV 文件 - JAX RS - REST - AJAX

java - 使用外部点查找矩形内部

python - 迭代配置文件中的部分