Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การนำเข้าข้อมูล (Importing Data) ใน Python

เมื่อรันโปรแกรม Python เราต้องใช้ dataset สำหรับ data analysis Python มีโมดูลต่างๆ ช่วยนำเข้าข้อมูลภายนอกในรูปแบบไฟล์ต่างๆ เข้าโปรแกรม Python ตัวอย่างนี้จะแสดงวิธีนำเข้าข้อมูลรูปแบบต่างๆ

นำเข้าไฟล์ CSV

โมดูล csv อ่านแต่ละแถวในไฟล์โดยใช้ comma เป็น delimiter เปิดไฟล์ read-only mode กำหนด delimiter แล้วใช้ for loop อ่านแต่ละแถว

ตัวอย่าง

import csv
with open("E:\\customers.csv", 'r') as custfile:
    rows = csv.reader(custfile, delimiter=',')
    for r in rows:
        print(r)

ผลลัพธ์

การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้ −

['customerID', 'gender', 'Contract', 'PaperlessBilling', 'Churn']
['7590-VHVEG', 'Female', 'Month-to-month', 'Yes', 'No']
['5575-GNVDE', 'Male', 'One year', 'No', 'No']
['3668-QPYBK', 'Male', 'Month-to-month', 'Yes', 'Yes']
['7795-CFOCW', 'Male', 'One year', 'No', 'No']
...

ใช้ pandas

ไลบรารี pandas จัดการไฟล์ส่วนใหญ่รวมถึง CSV ในตัวอย่างนี้ ดู pandas อ่านไฟล์ Excel ด้วย read_excel อ่านไฟล์ Excel เวอร์ชันของไฟล์ข้างต้น ได้ผลลัพธ์เหมือนกัน

ตัวอย่าง

import pandas as pd
df = pd.ExcelFile("E:\\customers.xlsx")
data = df.parse("customers")
print(data.head(10))

ผลลัพธ์

การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้ −

   customerID  gender      Contract PaperlessBilling Churn
0  7590-VHVEG  Female  Month-to-month              Yes    No
1  5575-GNVDE    Male        One year               No    No
2  3668-QPYBK    Male  Month-to-month              Yes   Yes
3  7795-CFOCW    Male        One year               No    No
4  9237-HQITU  Female  Month-to-month              Yes   Yes
5  9305-CDSKC  Female  Month-to-month              Yes   Yes
6  1452-KIOVK    Male  Month-to-month              Yes    No
7  6713-OKOMC  Female  Month-to-month               No    No
8  7892-POOKP  Female  Month-to-month              Yes   Yes
9  6388-TABGU    Male        One year               No    No

ใช้ pyodbc

เชื่อมต่อ database server ด้วยโมดูล pyodbc ช่วยนำเข้าจาก relational sources ด้วย SQL query ต้องกำหนด connection details ก่อนส่ง query

ตัวอย่าง

import pyodbc
sql_conn = pyodbc.connect("Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=sqldb;")
data_sql = pd.read_sql_query('SQL QUERY', sql_conn)
data_sql.head()

ผลลัพธ์

ขึ้นอยู่กับ SQL query จะแสดงผลตามนั้น