การนำเข้าไฟล์แบน (Flat Files) ด้วย NumPy

Python เบื้องต้น: การนำเข้าข้อมูล

Hugo Bowne-Anderson

Data Scientist at DataCamp

ทำไมต้องใช้ NumPy?

  • NumPy arrays: มาตรฐานสำหรับจัดเก็บข้อมูลตัวเลข

 

ch_1_3.003.png

Python เบื้องต้น: การนำเข้าข้อมูล

ทำไมต้องใช้ NumPy?

  • NumPy arrays: มาตรฐานสำหรับจัดเก็บข้อมูลตัวเลข
  • จำเป็นสำหรับแพ็กเกจอื่น เช่น scikit-learn ch_1_3.004.png
  • loadtxt()
  • genfromtxt()
Python เบื้องต้น: การนำเข้าข้อมูล

การนำเข้าไฟล์แบน (Flat Files) ด้วย NumPy

import numpy as np
filename = 'MNIST.txt'
data = np.loadtxt(filename, delimiter=',')
data
[[   0.    0.    0.    0.    0.]
 [  86.  250.  254.  254.  254.]
 [   0.    0.    0.    9.  254.]
 ..., 
 [   0.    0.    0.    0.    0.]
 [   0.    0.    0.    0.    0.]
 [   0.    0.    0.    0.    0.]]
Python เบื้องต้น: การนำเข้าข้อมูล

ปรับแต่งการนำเข้าด้วย NumPy

import numpy as np
filename = 'MNIST_header.txt'
data = np.loadtxt(filename, delimiter=',', skiprows=1)
print(data)
[[   0.    0.    0.    0.    0.]
 [  86.  250.  254.  254.  254.]
 [   0.    0.    0.    9.  254.]
 ..., 
 [   0.    0.    0.    0.    0.]
 [   0.    0.    0.    0.    0.]
 [   0.    0.    0.    0.    0.]]
  • skiprows: จำนวนแถว (ไม่ใช่ index) ที่ต้องการข้าม
Python เบื้องต้น: การนำเข้าข้อมูล

ปรับแต่งการนำเข้าด้วย NumPy

import numpy as np
filename = 'MNIST_header.txt'
data = np.loadtxt(filename, delimiter=',', skiprows=1, usecols=[0, 2])
print(data)
[[   0.    0.]
 [  86.  254.]
 [   0.    0.]
 ..., 
 [   0.    0.]
 [   0.    0.]
 [   0.    0.]]
  • usecols: รายการ index ของคอลัมน์ที่ต้องการเก็บไว้
Python เบื้องต้น: การนำเข้าข้อมูล

ปรับแต่งการนำเข้าด้วย NumPy

data = np.loadtxt(filename, delimiter=',', dtype=str)
Python เบื้องต้น: การนำเข้าข้อมูล

ประเภทข้อมูลผสม

titanic.csv

                        Name      Sex  Cabin   Fare
     Braund, Mr. Owen Harris     male    NaN    7.3
  Cumings, Mrs. John Bradley   female    C85   71.3
      Heikkinen, Miss. Laina   female    NaN    8.0
Futrelle, Mrs. Jacques Heath   female   C123   53.1
    Allen, Mr. William Henry     male    NaN   8.05


1 ที่มา: Kaggle
Python เบื้องต้น: การนำเข้าข้อมูล

ประเภทข้อมูลผสม

titanic.csv

                        Name      Sex  Cabin   Fare
     Braund, Mr. Owen Harris     male    NaN    7.3
  Cumings, Mrs. John Bradley   female    C85   71.3
      Heikkinen, Miss. Laina   female    NaN    8.0
Futrelle, Mrs. Jacques Heath   female   C123   53.1
    Allen, Mr. William Henry     male    NaN   8.05
               ^                                 ^
            strings                           floats
1 ที่มา: Kaggle
Python เบื้องต้น: การนำเข้าข้อมูล

มาฝึกกันเถอะ!

Python เบื้องต้น: การนำเข้าข้อมูล

Preparing Video For Download...