Read specific columns from a csv file with csv module?

后端 未结 12 1140
闹比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 11:09

    You can use numpy.loadtext(filename). For example if this is your database .csv:

    ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
    10 | Adam | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
    10 | Carl | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
    10 | Adolf | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
    10 | Den | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
    

    And you want the Name column:

    import numpy as np 
    b=np.loadtxt(r'filepath\name.csv',dtype=str,delimiter='|',skiprows=1,usecols=(1,))
    
    >>> b
    array([' Adam ', ' Carl ', ' Adolf ', ' Den '], 
          dtype='|S7')
    

    More easily you can use genfromtext:

    b = np.genfromtxt(r'filepath\name.csv', delimiter='|', names=True,dtype=None)
    >>> b['Name']
    array([' Adam ', ' Carl ', ' Adolf ', ' Den '], 
          dtype='|S7')
    

提交回复
热议问题