如何使用 Python 導入 Excel 文件數據

前言

隨著信息技術的快速發展,我們越來越需要從大量的 Excel 文件中提取數據,為了讓我們更加高效地處理 Excel 數據,Python 提供了操作 Excel 表格的庫。下面就介紹一下如何使用 Python 導入 Excel 文件數據。

準備環境

在使用 Python 操作 Excel 表格的庫之前,需要先在計算機上安裝以下兩個庫。

1. pandas

pandas 是 Python 中一個用於數據處理的庫,它可以處理 Excel、CSV 等各種類型的表格數據。

pip install pandas

2. openpyxl

openpyxl 是 Python 中一個用於讀寫 Excel 文件的庫。

pip install openpyxl

使用 pandas 讀取 Excel 文件數據

1. 讀取 Excel 文件

使用 pandas 庫中的 read_excel 方法可以直接讀取 Excel 文件里的數據。

import pandas as pd

# 讀取 Excel 文件
data = pd.read_excel('excel文件名')

2. 指定 sheet 表格

Excel 文件中可能包含多個 sheet 表,通過指定 sheetname 參數可以選擇讀取特定的 sheet。

import pandas as pd

# 讀取 Excel 文件中 sheet1
data = pd.read_excel('excel文件名', sheet_name='sheet1')

3. 指定讀取範圍

通過指定 nrows 和 usecols 參數可以選擇讀取特定的行或列。

import pandas as pd

# 讀取 Excel 文件中 sheet1 的前10行和第1、3列
data = pd.read_excel('excel文件名', sheet_name='sheet1', nrows=10, usecols=[0, 2])

4. Excel 文件中日期數據的讀取

Excel 中的日期格式與 Python 中的日期格式有所不同,需要使用 pandas 庫中的 to_datetime 方法進行轉換。

import pandas as pd

# 讀取Excel文件,指定『日期』列數據為日期格式
data = pd.read_excel('excel文件名', parse_dates=['日期'])

使用 openpyxl 讀取 Excel 文件數據

1. 打開 Excel 文件

使用 openpyxl 庫中的 load_workbook 方法可以打開 Excel 文件。

import openpyxl

# 打開 Excel 文件
wb = openpyxl.load_workbook('excel文件名')

2. 取得 sheet

使用 wb 對象的 get_sheet_by_name 方法可以取得 Excel 文件的一個 sheet。

import openpyxl

# 打開 Excel 文件
wb = openpyxl.load_workbook('excel文件名')

# 獲取 sheet1
ws = wb.get_sheet_by_name('sheet1')

3. 取得單元格數據

使用 ws 對象的 cell 方法可以取得單元格對象,使用 value 屬性可以取得單元格的值。

import openpyxl

# 打開 Excel 文件
wb = openpyxl.load_workbook('excel文件名')

# 獲取 sheet1
ws = wb.get_sheet_by_name('sheet1')

# 獲取A1單元格的值
value = ws.cell(row=1, column=1).value

4. 取得行數據

使用 ws 對象的 rows 屬性可以取得 sheet 的所有行,使用 for 循環可以遍歷所有行。

import openpyxl

# 打開 Excel 文件
wb = openpyxl.load_workbook('excel文件名')

# 獲取 sheet1
ws = wb.get_sheet_by_name('sheet1')

# 讀取 sheet1 所有行
for row in ws.rows:
    # do something

總結

以上就是如何使用 Python 導入 Excel 文件數據的方法,通過使用 pandas 和 openpyxl 庫可以很簡單地操作 Excel 表格。在使用 pandas 讀取 Excel 表格時,可以使用 read_excel 方法輕鬆讀取 Excel 表格數據;在使用 openpyxl 讀取 Excel 表格時,可以使用 load_workbook 方法打開 Excel 文件,使用 cell 方法讀取單元格數據,使用 rows 屬性讀取行數據。有了這些方法,我們可以很方便地將 Excel 表格數據導入到 Python 的數據分析工具中,對數據進行處理和分析。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/257422.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-15 12:45
下一篇 2024-12-15 12:45

相關推薦

發表回復

登錄後才能評論