【问题标题】:How to extract the specific columns from a csv file and write a new csv for it, in python如何在python中从csv文件中提取特定列并为其编写新的csv
【发布时间】:2013-02-11 13:22:22
【问题描述】:

我有一个 csv 文件,我想从中提取一些特定的列。我该怎么做?
我有一个标题字典和单元格位置,例如:

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

我想从dict的值开始提取数据,直到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 文件!请帮我这样做!
我想有效地处理这种情况!

【问题讨论】:

  • 这些索引是如何工作的? (5, 4) == 'klm'(4, 5) == ''),还是 (3, 4) == 'col1' ?然后,继续阅读专栏的规则是什么...也许您可以向我们展示您认为效率不高的当前代码...
  • 您可以使用csv.dictwritercsv.dictreaderdocs.python.org/2/library/csv.html.
  • 这类似于http://stackoverflow.com/questions/3209515/to-extract-specific-columns-from-a-csv-file-and-copy-it-to-another-using-python?rq=1

标签: python list memory csv dictionary


【解决方案1】:

Pandas 是一个库,具有强大的method 来读取 csv 文件。

如果您想从同一行读取每一列,以下脚本将完成工作(请注意,只有 2 行 python 有用):

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 2021-05-06
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多