在 Python 中匯入資料


在執行 Python 程式時,我們需要使用資料集進行資料分析。Python 有各種模組可以幫助我們將各種檔案格式的外部資料匯入到 Python 程式中。在本例中,我們將瞭解如何將各種格式的資料匯入到 Python 程式中。

匯入 csv 檔案

csv 模組使我們能夠使用逗號作為分隔符來讀取檔案中的每一行。我們首先以只讀模式開啟檔案,然後分配分隔符。最後,使用 for 迴圈從 csv 檔案中讀取每一行。

示例

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 庫如何使用 read_excel 模組處理 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

我們還可以使用名為 pyodbc 的模組連線到資料庫伺服器。這將幫助我們使用 sql 查詢從關係源匯入資料。當然,我們還必須在傳遞查詢之前定義到資料庫的連線詳細資訊。

示例

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 查詢,結果將顯示。

更新於:2020-07-10

16K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.