2013-02-26 422 views
-2

我有一個csv文件,我想從中提取一些特定的列。我怎樣才能做到這一點?
我有標題的字典和單元格位置,如:如何從csv文件中提取特定列併爲其寫入新的csv,在python中

dict = {'Col1' : [(4,5)], 'Col2' : [(4,7)], 'Col3' : [(4,9)]} 

我想提取數據從字典的值開始,直到CSV文件的結尾!

例如:

,,,,,,,,,, 
,,,,,,,,,, 
,,,,,,,,,, 
,,,Col0,Col1,,Col2,,Col3,Col4, 
,,,bgr,abc,,efg,,hij,123, 
,,,cde,klm,,nop,,qrs,123, 
,,,asd,tuv,,wxy,,zzz,456, 
,,,,,,,,,, 
,,,,,,,,,, 

我想提取

Col1,Col2,Col3 
abc,efg,hij 
klm,nop,qrs 
tuv,wxy,zzz 

,並在一個新的csv文件寫!請幫助我做到這一點!
我想有效地處理這種情況!

+0

如何那些索引工作? '(5,4)=='klm''和'(4,5)=='')',還是'(3,4)=='col1''?然後,繼續閱讀列的規則是什麼......也許你可以告訴我們你當前的代碼,你覺得效率不高...... – 2013-02-26 07:13:37

+0

你可以使用'csv.dictwriter'和'csv.dictreader'。 http://docs.python.org/2/library/csv.html。 – Gijs 2013-02-26 07:24:29

+0

這與'http://stackoverflow.com/questions/3209515/to-extract-specific-columns-from-a-csv-file-and-copy-it-to-another-using-python?rq= 1' – kvivek 2013-02-26 07:25:57

回答

1

Pandas是一個功能強大的method閱讀csv文件的庫。

在你想讀同一行每一列的情況下,下面的腳本將做的工作(注意,只有2蟒蛇線是有用的):

import pandas as pd 


# Give the name of the columns 
colnames = ('skip1', 'skip2', 'skip3', 'Col0','Col1','skip4','Col2','skip5','Col3','Col4','skip6') 
# Give the number of lines to skip 
nbskip=4 
# Give the number of rows to read (you can also filter rows after reading and remove the empty ones) 
nrows=3 
#List of columns to keep 
keep_only = ('Col1','Col2','Col3') 

#Read the csv 
df = pd.io.parsers.read_csv('test.csv', 
       header=None, 
       skiprows=nbskip, 
       names=colnames, 
       nrows=nrows, # Remove if you prefer filter rows 
       usecols=keep_only) 

# If the number of lines to keep is unknow, 
# you can remove empty lines here 

#Save the csv 
df.to_csv('result.csv', index=False) 
相關問題