在Python中處理表格數(shù)據(jù),有幾個非常流行且功能強大的庫。以下是一些最常用的庫及其示例代碼: 1. PandasPandas是一個開放源代碼的、BSD許可的庫,為Python編程語言提供高性能、易于使用的數(shù)據(jù)結構和數(shù)據(jù)分析工具。 安裝Pandaspip install pandas
示例代碼:讀取CSV文件import pandas as pd
# 讀取CSV文件 df = pd.read_csv('pokemon.csv')
# 顯示前五行數(shù)據(jù) print(df.head())
# 計算某列的平均值 print("Average of column:", df['Speed'].mean())
# 數(shù)據(jù)篩選 filtered_df = df[df['Speed'] > 10]
# 將更改后的DataFrame保存到新的CSV文件 filtered_df.to_csv('filtered_example.csv', index=False)
2. OpenPyXLOpenPyXL是一個庫,用于讀取和寫入Excel 2010 xlsx/xlsm/xltx/xltm文件。 安裝OpenPyXLpip install openpyxl
示例代碼:讀取Excel文件from openpyxl import load_workbook
# 加載一個現(xiàn)有的工作簿 wb = load_workbook('example.xlsx')
# 獲取活動的工作表 sheet = wb.active
# 讀取A1單元格的值 print(sheet['A1'].value)
# 修改B2單元格的值 sheet['B2'] = 42
# 保存工作簿 wb.save('modified_example.xlsx')
3. CSVPython標準庫中的CSV模塊提供了讀寫CSV文件的功能。 示例代碼:讀取CSV文件import csv
# 打開CSV文件 with open('example.csv', mode='r', encoding='utf-8') as file: reader = csv.reader(file) # 遍歷每一行 for row in reader: print(row)
# 寫入CSV文件 with open('output.csv', mode='w', encoding='utf-8', newline='') as file: writer = csv.writer(file) writer.writerow(['Name', 'Age', 'City']) writer.writerow(['Alice', '24', 'New York'])
4. xlrd/xlwt這兩個庫通常一起使用,xlrd用于讀取老版本的Excel文件(xls),而xlwt用于寫入。 安裝xlrd和xlwtpip install xlrd xlwt
示例代碼:讀取xls文件import xlrd
# 打開工作簿 wb = xlrd.open_workbook('catering_sale.xls')
# 通過索引獲取工作表 sheet = wb.sheet_by_index(0)
# 讀取A1單元格的值 print(sheet.cell_value(0, 0))
# 獲取行數(shù)和列數(shù) print(sheet.nrows, sheet.ncols)
當選擇庫的時候,最好考慮你的具體需求,例如文件格式(CSV、Excel等)、數(shù)據(jù)大小、性能需求以及是否需要進行復雜的數(shù)據(jù)分析和操作。Pandas在數(shù)據(jù)分析方面提供了廣泛的功能,而OpenPyXL、xlrd和xlwt則在處理Excel文件方面各有所長。標準庫中的CSV模塊足夠處理基本的CSV文件操作。
|