Read specific columns from a csv file with csv module?

后端 未结 12 964
闹比i
闹比i 2020-11-22 10:06

I\'m trying to parse through a csv file and extract the data from only specific columns.

Example csv:

ID | N         


        
12条回答
  •  太阳男子
    2020-11-22 10:55

    Thanks to the way you can index and subset a pandas dataframe, a very easy way to extract a single column from a csv file into a variable is:

    myVar = pd.read_csv('YourPath', sep = ",")['ColumnName']
    

    A few things to consider:

    The snippet above will produce a pandas Series and not dataframe. The suggestion from ayhan with usecols will also be faster if speed is an issue. Testing the two different approaches using %timeit on a 2122 KB sized csv file yields 22.8 ms for the usecols approach and 53 ms for my suggested approach.

    And don't forget import pandas as pd

提交回复
热议问题