Python将csv文件列读入列表,而忽略标题 [英] Python read csv file columns into lists, ignoring headers
本文介绍了Python将csv文件列读入列表,而忽略标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的文件'data.csv'
I have a file 'data.csv' that looks something like
ColA, ColB, ColC
1,2,3
4,5,6
7,8,9
我想打开文件列并将其读入列表,并省略该列表的第一个条目,例如
I want to open and read the file columns into lists, with the 1st entry of that list omitted, e.g.
dataA = [1,4,7]
dataB = [2,5,8]
dataC = [3,6,9]
实际上有3列以上,并且列表很长,这只是格式的一个示例.我尝试过:
In reality there are more than 3 columns and the lists are very long, this is just an example of the format. I've tried:
csv_file = open('data.csv','rb')
csv_array = []
for row in csv.reader(csv_file, delimiter=','):
csv_array.append(row)
然后我将csv_array
的每个索引分配给一个列表,例如
Where I would then allocate each index of csv_array
to a list, e.g.
dataA = [int(i) for i in csv_array[0]]
但是我遇到了错误:
_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?
感觉就像将数据保存到几个列表中一样漫长的方式...
Also it feels like a very long winded way of just saving data to a few lists...
谢谢!
这是我解决的方法:
import pandas as pd
df = pd.read_csv('data.csv', names = ['ColA','ColB','ColC']
dataA = map(int,(df.ColA.tolist())[1:3])
,然后对其余的列重复上述操作.
and repeat for the rest of the columns.
推荐答案
使用熊猫:
import pandas as pd
df = pd.DataFrame.from_csv(path)
rows = df.apply(lambda x: x.tolist(), axis=1)
这篇关于Python将csv文件列读入列表,而忽略标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文