Three ways to import csv data in Python

  • 2021-01-18 06:34:43
  • OfStack

There are three ways to import csv data in Python, as shown below:

1. Import CSV files from standard Python libraries:

Python provides a standard class library CSV files. The reader() function in this library is used to import the CSV file. When the CSV file is read in, this data can be used to generate an NumPy array that can be used to train the algorithm model. :


from csv importreader
import numpy as np
filename=input(" Please enter file name:  ")
withopen(filename,'rt',encoding='UTF-8')as raw_data:
  readers=reader(raw_data,delimiter=',')
  x=list(readers)
  data=np.array(x)
  print(data)
  print(data.shape)

2. Import CSV file via NumPy

You can also import data using the loadtxt() function of NumPy. The data processed using this function has no file header and all data structures are 1-like, that is, the data type is 1-like.


from numpy importloadtxt
filename=input(" The file name: ")
withopen(filename,'rt',encoding='UTF-8')as raw_data:
  data=loadtxt(raw_data,delimiter=',')
  print(data) 

3. Import CSV file via Pandas

Use Pandas to import CSV files from Pandas pandas.read_csv() Function. The return value of this function is ES34en, which is very convenient for the next step. It is recommended to use this method in practice.

In machine learning projects, Pandas is often used to do data cleaning and data preparation.


from pandas importread_csv
filename=input(" The file name: ")
f=open(filename,encoding='UTF-8')
names=[' Date of the homework ',' eta CO',' eta H2','TF( ℃ )','TC( ℃ )','mass',' Supply air flow rate ']
data=read_csv(f,names=names)
print(data)

conclusion


Related articles: