2016-11-22 179 views
1

是否可以在列中讀取csv文件而不是python中的行?Python閱讀列中的csv文件?

例如如果我有一個CSV文件是這樣的:

 
a b c 
1 0 1 
1 4 1 

一個人怎麼會得到[a,1,1],[b,0,4],[c,1,1]或者各種各樣的東西的清單?

+0

http://stackoverflow.com/questions/16503560/read-specific-columns- from-csv-file-with-python-csv這會回答你的問題 – WannaBeCoder

回答

3

您正在尋找轉置功能。爲了解決你的問題,

  1. 首先讀取CSV作爲行,在列表中 前創建行明智的元組:使用任何目前在Transpose a matrix in Python的解決方案[(a,b,c),(1,0,1),(1,4,1)..]
  2. 移調上面所列內容。

轉後,你的數據會看起來像[(a,1,1),(b,0,4)..]

0

您可以使用這樣的事情:

# Open file and read lines 
input_file = open('filename.csv') 
lines = input_file.readlines() 

# Create list with n sublists (n - number of columns) 
l = [[] for _ in lines[0].split('\t')] 

# Fill in sublists 
for line in lines: 
    for i, column in enumerate(line.split('\t')):  
     l[i].append(column) 
2

使用zip(*reader)

some.csv

a b c 
1 0 1 
1 4 1 

scrip.py

import csv 
with open('some.csv', 'rb') as f: 
    reader = csv.reader(f, delimiter=' ') 
    print zip(*reader) 

輸出:

[('a', '1', '1'), ('b', '0', '4'), ('c', '1', '1')]