Python處理Excel的14個(gè)常用操作總結(jié)
在數(shù)據(jù)處理和分析的領(lǐng)域中,Excel是一種被廣泛使用的工具。然而,通過(guò)Python處理Excel,能夠更好地實(shí)現(xiàn)自動(dòng)化和批量處理。本文將深入探討Python中處理Excel的14個(gè)常用操作,并提供詳盡的示例代碼,以助您更全面地掌握這些技能。
1. 讀取 Excel 文件
使用 pandas 庫(kù)讀取 Excel 文件是一種常見(jiàn)的數(shù)據(jù)處理操作,它能夠快速加載 Excel 中的表格數(shù)據(jù),并將其轉(zhuǎn)換為數(shù)據(jù)框架(DataFrame)。以下是一個(gè)簡(jiǎn)單的示例代碼,演示如何使用 pandas 讀取 Excel 文件。
import pandas as pd
# 讀取 Excel 文件
file_path = 'example_data.xlsx'
df = pd.read_excel(file_path)
# 打印讀取的數(shù)據(jù)框架
print("讀取的數(shù)據(jù)框架:")
print(df)
在這個(gè)例子中,使用 pd.read_excel 函數(shù)讀取了一個(gè)名為 ‘example_data.xlsx’ 的 Excel 文件。讀取后,數(shù)據(jù)被存儲(chǔ)在一個(gè) pandas 數(shù)據(jù)框架中。
2. 寫(xiě)入 Excel 文件
在處理數(shù)據(jù)后,將結(jié)果寫(xiě)入新的 Excel 文件是一項(xiàng)常見(jiàn)的任務(wù)。使用 pandas 庫(kù),可以將處理過(guò)的數(shù)據(jù)寫(xiě)入新的 Excel 文件。以下是一個(gè)簡(jiǎn)單的示例代碼,演示如何使用 pandas 將數(shù)據(jù)寫(xiě)入 Excel 文件。
import pandas as pd
# 創(chuàng)建示例數(shù)據(jù)框架
data = {
'Product': ['A', 'B', 'C'],
'Price': [25.5, 30.2, 15.8],
'Quantity': [10, 8, 4]
}
df = pd.DataFrame(data)
# 將數(shù)據(jù)框架寫(xiě)入 Excel 文件
df.to_excel('output_data.xlsx', index=False)
在這個(gè)例子中,使用 to_excel 函數(shù)將數(shù)據(jù)框架寫(xiě)入 Excel 文件。參數(shù) index=False 表示不包含行索引信息。生成的 Excel 文件名為 ‘output_data.xlsx’。
3. 數(shù)據(jù)篩選與過(guò)濾
在數(shù)據(jù)分析中,經(jīng)常需要根據(jù)特定條件篩選和過(guò)濾數(shù)據(jù),以便只保留感興趣的部分。使用 pandas 庫(kù),可以進(jìn)行數(shù)據(jù)篩選和過(guò)濾。以下是一個(gè)簡(jiǎn)單的示例代碼,演示如何使用 pandas 進(jìn)行數(shù)據(jù)篩選與過(guò)濾。
import pandas as pd
# 創(chuàng)建示例數(shù)據(jù)框架
data = {
'Product': ['A', 'B', 'C', 'A', 'B'],
'Price': [25.5, 30.2, 15.8, 22.0, 18.5],
'Quantity': [10, 8, 4, 6, 2]
}
df = pd.DataFrame(data)
# 篩選 Price 大于 20 的數(shù)據(jù)
filtered_data = df[df['Price'] > 20]
# 打印篩選后的數(shù)據(jù)框架
print("Price 大于 20 的數(shù)據(jù):")
print(filtered_data)
在這個(gè)例子中,使用了條件篩選,保留了 ‘Price’ 列大于 20 的行數(shù)據(jù)。你可以根據(jù)實(shí)際需求定義不同的篩選條件,以過(guò)濾符合條件的數(shù)據(jù)。
4. 數(shù)據(jù)排序
在 Excel 中,數(shù)據(jù)排序是一種常見(jiàn)的操作,可以更好地理解數(shù)據(jù)的結(jié)構(gòu)和趨勢(shì)。使用 pandas 庫(kù),可以對(duì)數(shù)據(jù)進(jìn)行排序。以下是一個(gè)簡(jiǎn)單的示例代碼,演示如何使用 pandas 對(duì)數(shù)據(jù)進(jìn)行排序。
import pandas as pd
# 創(chuàng)建示例數(shù)據(jù)框架
data = {
'Product': ['B', 'A', 'C', 'D', 'A'],
'Price': [30.2, 25.5, 15.8, 40.0, 20.5],
'Quantity': [8, 10, 4, 2, 6]
}
df = pd.DataFrame(data)
# 按 'Product' 列升序排序
df_sorted = df.sort_values(by='Product')
# 打印排序后的數(shù)據(jù)框架
print("按 'Product' 列升序排序:")
print(df_sorted)
在這個(gè)例子中,使用 sort_values 函數(shù)按 ‘Product’ 列的值進(jìn)行升序排序。也可以通過(guò)指定 ascending=False 參數(shù)來(lái)實(shí)現(xiàn)降序排序。這種排序方式使可以更容易地觀察數(shù)據(jù)的特征和趨勢(shì)。
5. 數(shù)據(jù)統(tǒng)計(jì)與匯總
通過(guò)pandas的統(tǒng)計(jì)函數(shù),可以快速了解數(shù)據(jù)的統(tǒng)計(jì)信息,如均值、中位數(shù)等。
假設(shè)有一個(gè)包含銷(xiāo)售數(shù)據(jù)的數(shù)據(jù)框架sales_data,其中包括產(chǎn)品銷(xiāo)售額(sales_amount)、銷(xiāo)售數(shù)量(quantity)和單價(jià)(unit_price)等列。我們將使用這個(gè)數(shù)據(jù)框架來(lái)演示如何進(jìn)行全面的數(shù)據(jù)統(tǒng)計(jì)與匯總。
import pandas as pd
# 假設(shè)我們有一個(gè)包含銷(xiāo)售數(shù)據(jù)的數(shù)據(jù)框架
data = {
'Product': ['A', 'B', 'C', 'A', 'B', 'A'],
'Sales_Amount': [100, 150, 200, 120, 180, 130],
'Quantity': [5, 3, 4, 6, 2, 5],
'Unit_Price': [20, 50, 50, 20, 90, 26]
}
sales_data = pd.DataFrame(data)
# 打印原始數(shù)據(jù)
print("原始數(shù)據(jù):")
print(sales_data)
# 統(tǒng)計(jì)與匯總
mean_sales_amount = sales_data['Sales_Amount'].mean()
median_quantity = sales_data['Quantity'].median()
mode_product = sales_data['Product'].mode().values[0]
std_unit_price = sales_data['Unit_Price'].std()
min_sales_amount = sales_data['Sales_Amount'].min()
max_quantity = sales_data['Quantity'].max()
# 打印統(tǒng)計(jì)結(jié)果
print("\n統(tǒng)計(jì)與匯總結(jié)果:")
print(f"平均銷(xiāo)售額:{mean_sales_amount}")
print(f"銷(xiāo)售數(shù)量中位數(shù):{median_quantity}")
print(f"產(chǎn)品銷(xiāo)售頻率最高的是:{mode_product}")
print(f"單價(jià)標(biāo)準(zhǔn)差:{std_unit_price}")
print(f"最小銷(xiāo)售額:{min_sales_amount}")
print(f"最大銷(xiāo)售數(shù)量:{max_quantity}")
這個(gè)例子中,使用了均值、中位數(shù)、眾數(shù)、標(biāo)準(zhǔn)差、最小值和最大值等統(tǒng)計(jì)方法來(lái)全面了解銷(xiāo)售數(shù)據(jù)的特征。通過(guò)運(yùn)用這些統(tǒng)計(jì)函數(shù),可以更好地理解數(shù)據(jù)的分布、趨勢(shì)和離散程度,為進(jìn)一步的數(shù)據(jù)分析和決策提供了基礎(chǔ)。
6. 單元格格式設(shè)置
在處理 Excel 數(shù)據(jù)時(shí),自定義單元格格式是提高數(shù)據(jù)可讀性和呈現(xiàn)效果的關(guān)鍵步驟。使用 openpyxl 庫(kù),可以輕松地對(duì) Excel 單元格進(jìn)行格式設(shè)置。下面是一些常見(jiàn)的單元格格式設(shè)置的例子。
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, PatternFill
# 創(chuàng)建一個(gè)工作簿和工作表
workbook = Workbook()
sheet = workbook.active
# 示例數(shù)據(jù)
data = [
["Product", "Price", "Quantity"],
["A", 25.5, 10],
["B", 30.2, 8],
["C", 15.8, 15],
]
# 將數(shù)據(jù)寫(xiě)入工作表
for row in data:
sheet.append(row)
# 單元格格式設(shè)置
# 設(shè)置標(biāo)題行的字體為粗體、字號(hào)14、顏色為藍(lán)色
sheet['A1'].font = Font(bold=True, size=14, color="0000FF")
# 設(shè)置數(shù)據(jù)區(qū)域的對(duì)齊方式為居中
for row in sheet.iter_rows(min_row=2, max_row=sheet.max_row, min_col=1, max_col=sheet.max_column):
for cell in row:
cell.alignment = Alignment(horizontal='center', vertical='center')
# 設(shè)置價(jià)格列的數(shù)值格式為貨幣格式
for row in sheet.iter_rows(min_row=2, max_row=sheet.max_row, min_col=2, max_col=2):
for cell in row:
cell.number_format = '"$"#,##0.00'
# 設(shè)置數(shù)量列的背景顏色為淺黃色
for row in sheet.iter_rows(min_row=2, max_row=sheet.max_row, min_col=3, max_col=3):
for cell in row:
cell.fill = PatternFill(start_color="FFFF99", end_color="FFFF99", fill_type="solid")
# 保存工作簿
workbook.save("formatted_excel.xlsx")
在這個(gè)例子中,通過(guò) Font、Alignment 和 PatternFill 類(lèi)來(lái)設(shè)置單元格的字體、對(duì)齊方式和背景顏色。這種格式設(shè)置使得 Excel 表格更加美觀、易讀,有助于突出數(shù)據(jù)的重要性和結(jié)構(gòu)??梢愿鶕?jù)實(shí)際需求調(diào)整這些設(shè)置,以滿足特定的數(shù)據(jù)展示要求。
7. 插入行與列
在處理 Excel 數(shù)據(jù)時(shí),插入新的行和列是保持?jǐn)?shù)據(jù)整潔和有序的關(guān)鍵步驟。使用 openpyxl 庫(kù),可以輕松地在 Excel 表格中插入新的行和列。以下是一些插入行和列的示例代碼。
插入新的行
from openpyxl import Workbook
# 創(chuàng)建一個(gè)工作簿和工作表
workbook = Workbook()
sheet = workbook.active
# 原始數(shù)據(jù)
data = [
["Name", "Age", "Country"],
["Alice", 25, "USA"],
["Bob", 30, "Canada"],
]
# 將數(shù)據(jù)寫(xiě)入工作表
for row in data:
sheet.append(row)
# 打印原始數(shù)據(jù)
print("原始數(shù)據(jù):")
for row in sheet.iter_rows(values_only=True):
print(row)
# 插入新的行(在第二行之后插入)
new_row_data = ["Charlie", 28, "UK"]
sheet.insert_rows(new_row_data, row_idx=2)
# 打印插入新行后的數(shù)據(jù)
print("\n插入新行后的數(shù)據(jù):")
for row in sheet.iter_rows(values_only=True):
print(row)
# 保存工作簿
workbook.save("inserted_row.xlsx")
插入新的列
from openpyxl import Workbook
# 創(chuàng)建一個(gè)工作簿和工作表
workbook = Workbook()
sheet = workbook.active
# 原始數(shù)據(jù)
data = [
["Name", "Age", "Country"],
["Alice", 25, "USA"],
["Bob", 30, "Canada"],
]
# 將數(shù)據(jù)寫(xiě)入工作表
for row in data:
sheet.append(row)
# 打印原始數(shù)據(jù)
print("原始數(shù)據(jù):")
for row in sheet.iter_rows(values_only=True):
print(row)
# 插入新的列(在第二列之后插入)
new_column_data = ["Female", "Male", "Female"]
sheet.insert_cols(values=new_column_data, col_idx=2)
# 打印插入新列后的數(shù)據(jù)
print("\n插入新列后的數(shù)據(jù):")
for row in sheet.iter_rows(values_only=True):
print(row)
# 保存工作簿
workbook.save("inserted_column.xlsx")
這些示例代碼演示了如何使用 insert_rows 和 insert_cols 方法在 Excel 表格中插入新的行和列。
8. 合并單元格
在 Excel 中,合并單元格是一種常用的操作,用于創(chuàng)建更復(fù)雜的表格結(jié)構(gòu)或突出某些信息。使用 openpyxl 庫(kù),可以實(shí)現(xiàn)合并和取消合并單元格的操作。以下是一些合并單元格的示例代碼。
合并單元格
from openpyxl import Workbook
# 創(chuàng)建一個(gè)工作簿和工作表
workbook = Workbook()
sheet = workbook.active
# 原始數(shù)據(jù)
data = [
["Name", "Age", "Country"],
["Alice", 25, "USA"],
["Bob", 30, "Canada"],
]
# 將數(shù)據(jù)寫(xiě)入工作表
for row in data:
sheet.append(row)
# 合并 A1 到 C1 的單元格
sheet.merge_cells('A1:C1')
# 在合并的單元格中寫(xiě)入標(biāo)題
sheet['A1'] = 'Personal Information'
# 保存工作簿
workbook.save("merged_cells.xlsx")
取消合并單元格
from openpyxl import load_workbook
# 加載已存在的工作簿
workbook = load_workbook("merged_cells.xlsx")
sheet = workbook.active
# 取消合并 A1 到 C1 的單元格
sheet.unmerge_cells('A1:C1')
# 保存工作簿
workbook.save("unmerged_cells.xlsx")
在這個(gè)示例中,首先合并了 A1 到 C1 的單元格,創(chuàng)建了一個(gè)包含標(biāo)題的大標(biāo)題單元格。然后,演示了如何取消合并這些單元格。這種操作使得表格的布局更加靈活,可以根據(jù)實(shí)際需要進(jìn)行定制。
9. 公式計(jì)算
在 Excel 中添加公式是一種常見(jiàn)的操作,可以實(shí)現(xiàn)自動(dòng)計(jì)算,并隨著數(shù)據(jù)的更新而動(dòng)態(tài)調(diào)整。使用 openpyxl 庫(kù),可以輕松地在 Excel 中插入公式。以下是一個(gè)添加公式的示例代碼。
from openpyxl import Workbook
# 創(chuàng)建一個(gè)工作簿和工作表
workbook = Workbook()
sheet = workbook.active
# 原始數(shù)據(jù)
data = [
["Product", "Price", "Quantity", "Total"],
["A", 25.5, 10, None],
["B", 30.2, 8, None],
]
# 將數(shù)據(jù)寫(xiě)入工作表
for row in data:
sheet.append(row)
# 添加公式計(jì)算 Total 列,Total = Price * Quantity
for row in range(2, sheet.max_row + 1):
sheet[f'D{row}'] = f'B{row} * C{row}'
# 保存工作簿
workbook.save("formulas.xlsx")
在這個(gè)例子中,通過(guò)循環(huán)遍歷數(shù)據(jù)行,使用 Excel 公式 B(row) * C(row) 來(lái)計(jì)算 Total 列的值。這樣,無(wú)論數(shù)據(jù)如何變化,Total 列都會(huì)自動(dòng)更新。這種功能使得在 Excel 中進(jìn)行復(fù)雜的數(shù)據(jù)計(jì)算變得更加方便和靈活。
10. 圖表繪制
在 Excel 中插入圖表是一種直觀且生動(dòng)的方式,可以更清晰地展示數(shù)據(jù)的趨勢(shì)和關(guān)系。使用 openpyxl 和 matplotlib 庫(kù),可以將數(shù)據(jù)可視化為圖表,并插入到 Excel 工作表中。以下是一個(gè)插入柱狀圖的示例代碼。
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference
import matplotlib.pyplot as plt
from io import BytesIO
# 創(chuàng)建一個(gè)工作簿和工作表
workbook = Workbook()
sheet = workbook.active
# 原始數(shù)據(jù)
data = [
["Category", "Value"],
["A", 25],
["B", 30],
["C", 20],
]
# 將數(shù)據(jù)寫(xiě)入工作表
for row in data:
sheet.append(row)
# 創(chuàng)建柱狀圖
chart = BarChart()
chart.title = "Category vs Value"
chart.x_axis.title = "Category"
chart.y_axis.title = "Value"
# 數(shù)據(jù)范圍
data_range = Reference(sheet, min_col=2, min_row=1, max_col=2, max_row=sheet.max_row)
# 設(shè)置圖表數(shù)據(jù)
chart.add_data(data_range, titles_from_data=True)
# 將圖表插入到工作表中
sheet.add_chart(chart, "D2")
# 保存工作簿
workbook.save("chart_example.xlsx")
在這個(gè)示例中,創(chuàng)建了一個(gè)包含柱狀圖的 Excel 工作表。首先,使用 BarChart 創(chuàng)建一個(gè)柱狀圖對(duì)象,然后設(shè)置圖表的標(biāo)題、X軸標(biāo)題和Y軸標(biāo)題。接著,通過(guò) Reference 定義數(shù)據(jù)范圍,并使用 add_data 將數(shù)據(jù)添加到圖表中。最后,使用 add_chart 將圖表插入到工作表中。這樣,就能夠在 Excel 中通過(guò)圖表直觀地展示數(shù)據(jù)的分布和關(guān)系。
11. 數(shù)據(jù)透視表
數(shù)據(jù)透視表是一種強(qiáng)大的數(shù)據(jù)分析工具,可以幫助我們快速透視和匯總數(shù)據(jù)。使用 pandas 的 pivot_table 函數(shù),可以在 Python 中輕松創(chuàng)建數(shù)據(jù)透視表。以下是一個(gè)簡(jiǎn)單的示例代碼。
import pandas as pd
# 創(chuàng)建示例數(shù)據(jù)框架
data = {
'Category': ['A', 'B', 'A', 'B', 'A', 'B'],
'Value': [10, 15, 20, 25, 30, 35],
'Quantity': [2, 3, 4, 5, 6, 7]
}
df = pd.DataFrame(data)
# 創(chuàng)建數(shù)據(jù)透視表
pivot_table = pd.pivot_table(df, values='Value', index='Category', columns='Quantity', aggfunc='sum', fill_value=0)
# 打印數(shù)據(jù)透視表
print("數(shù)據(jù)透視表:")
print(pivot_table)
在這個(gè)例子中,我們使用 pivot_table 函數(shù)根據(jù) ‘Category’ 和 ‘Quantity’ 列創(chuàng)建了一個(gè)數(shù)據(jù)透視表。我們指定了值列為 ‘Value’,使用 ‘sum’ 函數(shù)進(jìn)行匯總,如果某些組合不存在則用 0 填充。最后,打印了生成的數(shù)據(jù)透視表。
12. 數(shù)據(jù)驗(yàn)證
在 Excel 中設(shè)置數(shù)據(jù)驗(yàn)證規(guī)則是一種有效的方式,可以確保用戶輸入的數(shù)據(jù)符合預(yù)期的范圍或格式。使用 openpyxl 庫(kù),可以添加數(shù)據(jù)驗(yàn)證規(guī)則。以下是一個(gè)簡(jiǎn)單的示例代碼,演示如何在 Excel 中設(shè)置數(shù)據(jù)驗(yàn)證規(guī)則。
from openpyxl import Workbook
from openpyxl.worksheet.datavalidation import DataValidation
# 創(chuàng)建一個(gè)工作簿和工作表
workbook = Workbook()
sheet = workbook.active
# 原始數(shù)據(jù)
data = [
["Name", "Age", "Country"],
["Alice", 25, "USA"],
["Bob", 30, "Canada"],
]
# 將數(shù)據(jù)寫(xiě)入工作表
for row in data:
sheet.append(row)
# 創(chuàng)建數(shù)據(jù)驗(yàn)證規(guī)則(Age 列只允許輸入 18 到 60 之間的整數(shù))
dv = DataValidation(type="whole", operator="between", formula1=18, formula2=60)
dv.errorTitle = "Invalid Input"
dv.error = "Age must be between 18 and 60."
dv.add("B2:B1048576") # 應(yīng)用規(guī)則到整個(gè) B 列
# 添加數(shù)據(jù)驗(yàn)證規(guī)則到工作表
sheet.add_data_validation(dv)
# 保存工作簿
workbook.save("data_validation_example.xlsx")
在這個(gè)例子中,使用 DataValidation 類(lèi)創(chuàng)建了一個(gè)數(shù)據(jù)驗(yàn)證規(guī)則,要求在 ‘B’ 列(Age 列)中輸入整數(shù),并且范圍必須在 18 到 60 之間。然后,將這個(gè)規(guī)則應(yīng)用到整個(gè) ‘B’ 列。這樣,用戶在輸入數(shù)據(jù)時(shí),將受到相應(yīng)范圍和格式的限制,提高了數(shù)據(jù)的準(zhǔn)確性。
13. 批量操作
批量操作是在 Excel 中處理大量數(shù)據(jù)時(shí)提高效率的關(guān)鍵。使用循環(huán)和函數(shù),可以對(duì)數(shù)據(jù)進(jìn)行批量處理。以下是一個(gè)簡(jiǎn)單的示例代碼,演示如何使用循環(huán)和函數(shù)批量操作 Excel 數(shù)據(jù)。
from openpyxl import Workbook
# 創(chuàng)建一個(gè)工作簿和工作表
workbook = Workbook()
sheet = workbook.active
# 原始數(shù)據(jù)
data = [
["Product", "Price", "Quantity", "Total"],
["A", 25.5, 10, None],
["B", 30.2, 8, None],
]
# 將數(shù)據(jù)寫(xiě)入工作表
for row in data:
sheet.append(row)
# 批量計(jì)算 Total 列的值(Total = Price * Quantity)
for row in range(2, sheet.max_row + 1):
price = sheet[f'B{row}'].value
quantity = sheet[f'C{row}'].value
total = price * quantity
sheet[f'D{row}'] = total
# 打印批量計(jì)算后的數(shù)據(jù)
print("批量計(jì)算后的數(shù)據(jù):")
for row in sheet.iter_rows(values_only=True):
print(row)
# 保存工作簿
workbook.save("batch_operations.xlsx")
在這個(gè)例子中,使用循環(huán)遍歷數(shù)據(jù)行,并批量計(jì)算了 ‘Total’ 列的值。通過(guò)使用循環(huán),可以對(duì)整個(gè)數(shù)據(jù)集進(jìn)行高效的操作,而不需要逐個(gè)手動(dòng)處理每一行數(shù)據(jù)。
14. 錯(cuò)誤處理
在處理 Excel 數(shù)據(jù)時(shí),錯(cuò)誤是不可避免的。為了提高代碼的健壯性,可以使用異常處理機(jī)制來(lái)處理可能出現(xiàn)的錯(cuò)誤。以下是一個(gè)簡(jiǎn)單的示例代碼,演示如何使用異常處理來(lái)處理 Excel 操作中的錯(cuò)誤。
from openpyxl import Workbook
try:
# 創(chuàng)建一個(gè)工作簿和工作表
workbook = Workbook()
sheet = workbook.active
# 原始數(shù)據(jù)
data = [
["Product", "Price", "Quantity", "Total"],
["A", 25.5, 10, None],
["B", 30.2, 8, None],
]
# 將數(shù)據(jù)寫(xiě)入工作表
for row in data:
sheet.append(row)
# 嘗試計(jì)算 Total 列的值,但存在空值導(dǎo)致的錯(cuò)誤
for row in range(2, sheet.max_row + 1):
try:
price = sheet[f'B{row}'].value
quantity = sheet[f'C{row}'].value
total = price * quantity
sheet[f'D{row}'] = total
except TypeError as e:
print(f"Error in row {row}: {e}")
# 打印處理后的數(shù)據(jù)
print("處理后的數(shù)據(jù):")
for row in sheet.iter_rows(values_only=True):
print(row)
# 保存工作簿
workbook.save("error_handling_example.xlsx")
except Exception as e:
print(f"An error occurred: {e}")
在這個(gè)例子中,使用了兩層異常處理。外層的異常處理捕獲了可能發(fā)生的任何異常,而內(nèi)層的異常處理僅捕獲特定的 TypeError,這是由于在計(jì)算 ‘Total’ 列時(shí)可能遇到的錯(cuò)誤類(lèi)型。
總結(jié)
在這篇博客中,分享了使用 Python 處理 Excel 數(shù)據(jù)的各種技巧和方法。首先,學(xué)習(xí)了如何使用 pandas 庫(kù)讀取 Excel 文件,將表格數(shù)據(jù)轉(zhuǎn)換為數(shù)據(jù)框架,為后續(xù)處理打下了基礎(chǔ)。接著,介紹了數(shù)據(jù)篩選與過(guò)濾的方法,利用條件篩選功能,輕松地過(guò)濾和保留感興趣的數(shù)據(jù)。然后,學(xué)習(xí)了數(shù)據(jù)排序的操作,通過(guò) pandas 的排序功能,使數(shù)據(jù)更具可讀性,更容易理解數(shù)據(jù)的結(jié)構(gòu)和趨勢(shì)。
還分享了數(shù)據(jù)的批量操作,通過(guò)循環(huán)和函數(shù),高效地對(duì) Excel 數(shù)據(jù)進(jìn)行批量處理,提高了代碼的復(fù)用性和效率。學(xué)習(xí)了如何利用 pandas 的數(shù)據(jù)透視表功能,輕松進(jìn)行數(shù)據(jù)透視和匯總,以及如何通過(guò)數(shù)據(jù)驗(yàn)證規(guī)則提高數(shù)據(jù)的準(zhǔn)確性。
進(jìn)一步,了解了如何處理 Excel 中的錯(cuò)誤,通過(guò)異常處理機(jī)制提高代碼的健壯性,確保在面對(duì)異常情況時(shí)程序能夠正常執(zhí)行。最后,學(xué)習(xí)了如何將處理過(guò)的數(shù)據(jù)寫(xiě)入新的 Excel 文件,為數(shù)據(jù)的分享和進(jìn)一步分析提供了便捷的方式。
通過(guò)這些技巧和方法,我們能夠在 Python 中更靈活、高效地處理和分析 Excel 數(shù)據(jù),為數(shù)據(jù)科學(xué)和數(shù)據(jù)處理工作提供了豐富的工具和思路。無(wú)論是初學(xué)者還是有經(jīng)驗(yàn)的開(kāi)發(fā)者,這些技能都將為處理實(shí)際工作中的 Excel 數(shù)據(jù)提供強(qiáng)大的支持。
以上就是Python處理Excel的14個(gè)常用操作總結(jié)的詳細(xì)內(nèi)容,更多關(guān)于Python處理Excel的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
這篇文章主要介紹了python3連接MySQL8.0的兩種方式,本文通過(guò)多種方式給大家介紹的非常詳細(xì),代碼附有文字注釋?zhuān)枰呐笥芽梢詤⒖枷?/div> 2020-02-02
python 串行執(zhí)行和并行執(zhí)行實(shí)例
這篇文章主要介紹了python 串行執(zhí)行和并行執(zhí)行實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04
用python批量生成文件夾的實(shí)現(xiàn)方法舉例
這篇文章主要介紹了使用Python腳本批量生成文件夾的方法,可以用于創(chuàng)建順序文件夾或嵌套文件夾,通過(guò)設(shè)置路徑和循環(huán),可以自動(dòng)命名并創(chuàng)建文件夾,提高工作效率,需要的朋友可以參考下2025-03-03
Python編程求解二叉樹(shù)中和為某一值的路徑代碼示例
這篇文章主要介紹了Python編程求解二叉樹(shù)中和為某一值的路徑代碼示例,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
Python動(dòng)刷新12306火車(chē)票的代碼(附源碼)
這篇文章主要介紹了Python動(dòng)刷新12306火車(chē)票的完整代碼,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧2018-01-01最新評(píng)論

