SoFunction
Updated on 2024-11-16

Example of python reading .csv file data into an array (matrix)

Utilizing the numpy library

(drawback: unreadable with missing values)

Read:

import numpy 
my_matrix = (open("","rb"),delimiter=",",skiprows=0) 

Write:

('', my_matrix, delimiter = ',')

Problems likely to be encountered:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position

The reason is that the file path name contains escape characters, replace \ with \ in the path can be.

Utilizing the pandas library

Read: (can handle missing values)

>>> import pandas as pd
>>> df = pd.read_csv('D:\Python\\l\B_train1.csv')
>>> 
>>> df.as_matrix(columns=None)

Write: (write the dataFrame directly)

>>> testB = test[test.intersection_id.isin(["B"])]
>>> .to_csv(testB,"D:\Python\\k\\")
#testBIt's a...dataFrame

Handling missing values with Imputer from the sklearn package

>>> m = df.as_matrix(columns=None)
>>> from  import Imputer
>>> imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
>>> (m)
Imputer(axis=0, copy=True, missing_values='NaN', strategy='mean', verbose=0)
>>> (m)

Above this python read .csv file data to an array (matrix) of examples to explain is all I have shared with you, I hope to be able to give you a reference, and I hope you can support me more.