load csv file to numpy and access columns by name

前端 未结 2 872
日久生厌
日久生厌 2021-01-12 01:27

I have a csv file with headers like:

Given this test.csv file:

\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"timestamp\"
611.88243,         


        
2条回答
  •  青春惊慌失措
    2021-01-12 02:02

    Because your data is homogeneous--all the elements are floating point values--you can create a view of the data returned by genfromtxt that is a 2D array. For example,

    In [42]: r = np.genfromtxt("test.csv", delimiter=',', names=True)
    

    Create a numpy array that is a "view" of r. This is a regular numpy array, but it is created using the data in r:

    In [43]: a = r.view(np.float64).reshape(len(r), -1)
    
    In [44]: a.shape
    Out[44]: (3, 7)
    
    In [45]: a[:, 0]
    Out[45]: array([ 611.88243,  611.88243,  611.88243])
    
    In [46]: r['A']
    Out[46]: array([ 611.88243,  611.88243,  611.88243])
    

    r and a refer to the same block of memory:

    In [47]: a[0, 0] = -1
    
    In [48]: r['A']
    Out[48]: array([  -1.     ,  611.88243,  611.88243])
    

提交回复
热议问题