Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Nhập dữ liệu trong Python

Khi chạy chương trình Python, cần dataset cho phân tích dữ liệu. Python có nhiều module hỗ trợ nhập dữ liệu ngoại vi đa dạng định dạng.

Nhập file CSV

Module csv đọc từng hàng với delimiter comma. Mở file read-only, gán delimiter, for loop đọc từng hàng.

Ví dụ

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

Kết quả

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

Với pandas

pandas xử lý hầu hết định dạng file包括 CSV, Excel. Dùng read_excel.

Ví dụ

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

Kết quả

   customerID gender   Contract PaperlessBilling Churn
0  7590-VHVEG Female Month-to-month Yes No
1  5575-GNVDE Male   One year     No  No
...

Với pyodbc

Kết nối database server qua pyodbc, nhập dữ liệu từ nguồn quan hệ dùng SQL query.

Ví dụ

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()

Kết quả

Tùy SQL query mà hiển thị kết quả.