繁体   English   中英

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

[英]Converting vertical headers to horizontal in csv

我是 Python 的新手。 我有一个 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

但我需要以这种格式生成 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

我不知道如何进一步进行。 任何人都可以帮我解决这个问题吗?

似乎最简单的方法是首先读取输入文件中的数据并将其转换为列表列表,每个子列表对应于输出 csv 文件中的一列数据。 子列表将从列的标题开始,然后是下一行中与其关联的值。

完成后,内置的zip()函数可用于转置创建的数据矩阵。 此操作有效地将其包含的数据列转换为写入 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