简体   繁体   English

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

[英]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.

相关问题 python csv文件读取:将第一行变成列标题,next(reader)返回不需要的字符 - python csv file reading: turning the first row into column headers, next(reader) returns unwanted characters 将 dataframe 中的第一行添加到列标题 - Adding first row in dataframe to column headers Python:将列表写入csv,将第一行换成一列 - Python: write list to csv, transposing the first row into a column 如何使用带有完整标题的python导入csv文件,其中第一列是非数字 - How to import a csv file using python with headers intact, where first column is a non-numerical 如何在python中传递csv文件的第一列 - How to pass the first column of a csv file in python 仅在所有元素为 0 的矩阵的第一行和第一列中添加元素 - Adding elements only in first row and first column of a matrix with all elements 0 如何在csv文件中搜索特定的列值(如果存在),使用Python将前两个列值写入新的csv文件? - How to search for a specific column value in csv file, if present , write first two column values to a new csv file with Python? 在 pandas 列标题上方插入一行以在 csv / excel 文件的第一个单元格中保存标题名称 - Inserting a row above pandas column headers to save a title name in the first cell of csv / excel file 第一行未被识别为列标题 - First row not recognized as column headers 将 CSV 文件作为包含第一行作为标题(键)的字典读取 - Read CSV file as a dictionary containing first row as headers (keys)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM