简体   繁体   English

在csv中将垂直标题转换为水平标题

[英]Converting vertical headers to horizontal in csv

I am new to Python.我是 Python 的新手。 I have a csv file which will generate the file in below format:我有一个 csv 文件,它将以以下格式生成文件:

Timestamp for usage of CPU
1466707823  1466707828  1466707833

Percent use for CPU# 0
0.590551162 0.588235305 0.59055119

Percent use for CPU# 1
7.874015497 7.843137402 7.67716547

But I need to generate csv file in this format:但我需要以这种格式生成 csv 文件:

Timestamp for usage of CPU    Percent use for CPU# 0    Percent use for CPU# 1

1466707823                    0.590551162               7.874015497

1466707823                    0.588235305               7.843137402

1466707828                    0.59055119                7.67717547

I am not getting any idea how to proceed further.我不知道如何进一步进行。 Could any one please help me out with this?任何人都可以帮我解决这个问题吗?

It seems like the simplest way to do it would be to first read and convert the data in the input file into a list of lists with each sublist corresponding to a column of data in the output csv file.似乎最简单的方法是首先读取输入文件中的数据并将其转换为列表列表,每个子列表对应于输出 csv 文件中的一列数据。 The sublists will start off with the column's header and then be followed by the values associated with it from the next line.子列表将从列的标题开始,然后是下一行中与其关联的值。

Once that is done, the built-in zip() function can be used to transpose the data matrix created.完成后,内置的zip()函数可用于转置创建的数据矩阵。 This operation effectively turns the columns of data it contains into the rows of data needed for writing out to the csv file:此操作有效地将其包含的数据列转换为写入 csv 文件所需的数据行:

import csv

def is_numeric_string(s):
    """ Determine if argument is a string representing a numeric value. """
    for kind in (int, float, complex):
        try:
            kind(s)
        except (TypeError, ValueError):
            pass
        else:
            return True
    else:
        return False

columns = []
with open('not_a_csv.txt') as f:
    for line in (line.strip() for line in f):
        fields = line.split()
        if fields:  # non-blank line?
            if is_numeric_string(fields[0]):
                columns[-1] += fields  # add fields to the new column
            else:  # start a new column with this line as its header
                columns.append([line])

rows = zip(*columns)  # transpose
with open('formatted.csv', 'w') as f:
    csv.writer(f, delimiter='\t').writerows(rows)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM