我有一个csv
这样的文件:
Time | Temperature
0.0 | 15.2
3.0 | 16.1
6.0 | 14.8
9.0 | 20.2
现在我想打印/返回它:(["Time", "Temperature"], [[0.0, 3.0, 6.0, 9.0], [15.2, 16.1, 14.8, 20.2]])
但是python-docs的代码只返回了这个:
['Time', 'Temperature']
['0.0', '15.2']
['3.0', '16.1']
['6.0', '14.8']
['9.0', '20.2']
如何将其转换为一个列表?
编辑:我写了一个类,对于我的问题,我使用“parse_csv”方法:import csv
class Table:
def __init__(self, titles=None, cols=None, filename = None):
self.titles = titles
self.cols = cols
self.filename = filename
def __str__(self):
return (str(self.titles) +', '+ str(self.cols))
def __eq__(self, other):
try:
return (self.titles, self.cols) == (other.titles, other.cols)
except AttributeError:
return NotImplemented
def parse_csv(self, filename):
with open(filename, newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
return row
EDIT2:我用这个检查代码:
titles = ["Time", "Temperature"]
filename1 = "simple_example.csv"
my_table1 = Table(titles, [[0.0, 3.0, 6.0, 9.0], [15.2, 16.1, 14.8, 20.2]])
my_table2 = Table(filename = "simple_example.csv")
assert my_table2 == my_table3
答案 0 :(得分:1)
我假设您要将标题[column1和column2]作为元组返回。你可以用熊猫轻松完成。
import pandas as pd
def parse_csv(file_name):
df = pd.read_csv(file_name)
time = df['Time'].as_matrix().tolist() #returns the time column as a list
temperature = df['Temperature'].as_matrix().tolist() #returns the temperature column as a list
header = list(df.columns.values) #returns the header values as a list
return (header, [time, temperature]) #returning a tuple
答案 1 :(得分:0)
这是你应该如何定义你的类并初始化它。
import csv
class Table:
def __init__(self, titles=None, cols=None, filename = None):
self.titles = titles
self.cols = cols
self.filename = filename
def __str__(self):
return (str(self.titles) +', '+ str(self.cols))
def __eq__(self, other):
try:
return (self.titles, self.cols) == (other.titles, other.cols)
except AttributeError:
return NotImplemented
def parse_csv(self, filename=None):
if not filename:
filename=self.filename
with open(filename, newline='') as csvfile:
reader = csv.reader(csvfile, delimiter='|')
line = [[a.strip() for a in line] for line in reader]
self.titles= line[0]
self.cols = [list(a) for a in zip(*line[1:])]
self.cols = [[float(b) for b in c] for c in self.cols]
titles = ["Time", "Temperature"]
filename1 = "simple_example.csv"
my_table1 = Table(titles, cols=[[0.0, 3.0, 6.0, 9.0], [15.2, 16.1, 14.8, 20.2]])
my_table2 = Table(filename="simple_example.csv")
my_table2.parse_csv()
print my_table1 == my_table2
输出:
True
答案 2 :(得分:0)
我想这就是你想要实现的目标:
import csv
def parse_csv(filename):
with open(filename) as f:
reader = csv.reader(f)
header = next(reader)
cols = list(zip(*reader))
return [header, cols]
next
返回reader迭代器的第一个元素(标题行),然后zip
转换列向量中的剩余行。
答案 3 :(得分:0)
使用zip()
函数的解决方案:
with open('test.csv', 'r') as fh:
contents = list(csv.reader(fh, delimiter='|', quotechar='|'))
result = []
result.append(contents.pop(0))
result.append([list(s) for s in list(zip(*contents))])
print(result)
输出:
[['Time ', ' Temperature'], [['0.0 ', '3.0 ', '6.0 ', '9.0 '], [' 15.2', ' 16.1', ' 14.8', ' 20.2']]]
答案 4 :(得分:0)
a=open('filepath','r')
final,timel,templ,count=[],[],[],0
for l in a:
c=l.split(',')
if count >=1:
timel.append(float(c[0]))
templ.append(float(c[1]))
if count==0: #this is just to append the header in the final result
c[1]=c[1][:-1] #to remove the '\n'
final.append(c)
count+=1
final.append([timel,templ])
final=tuple(final)
print(final)
答案 5 :(得分:-1)
import numpy as np
y = np.array(x)
z = [y[0],y[1:,0],y[1:,1]]
res = [i.tolist() for i in z]
print res