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