Convert csv file to array and slice of array

In Python we often use two libraries Numpy and pandas

Convert csv file to array

import numpy
my_matrix = numpy.loadtxt(open( "c:\\1.csv" , "rb" ),delimiter= "," ,skiprows= 0 ) //The CSV file is converted to an array
 
 

Storing an array or matrix as a csv file can be implemented using the following code:

numpy.savetxt('new.csv', my_matrix, delimiter = ',')
 
 

 
 

slice of array

Array slices are views of the original array, meaning that the data will not be copied, and any modifications to the view will be directly reflected on the original array:

1D array slice

>>> arr2=np.arange(10)>>> arr2array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>>> arr2[5:8]array([5, 6, 7])>>> arr[5:8]=12>>> arr2array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>>> arr_slice=arr2[5:8]>>> arr_slice[1]=12345>>> arr2array([    0,     1,     2,     3,     4,    12, 12345,    12,     8,     9])>>> arr_slice[:]=64>>> arr2array([ 0,  1,  2,  3,  4, 64, 64, 64,  8,  9])

2D array slice

2D slices are axis-dependent and can be sliced ​​on one or more axes

>>> import numpy as np
>>> arr = np.arange(12).reshape((3, 4))
>>> print(arr)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
>>> slice_one = arr[1:2, 1:3]
>>> print(slice_one)
[[5 6]]
>>> arr[:2]
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
>>> arr[:2,1:]
array([[1, 2, 3],
       [5, 6, 7]])


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325856410&siteId=291194637