在Python中创建和操作表格有多种方法,以下是几种常用的库和方法:
pandas 创建表格
```python
import pandas as pd
data = {
'姓名': ['小王', '小李', '小张'],
'年龄': [25, 28, 22],
'工资': [8000, 12000, 7500]
}
df = pd.DataFrame(data)
print(df)
```
从文件创建表格:
```python
df = pd.read_csv('员工信息.csv')
df.to_excel('员工信息.xlsx', index=False)
```
表格操作:
```python
df['奖金'] = df['工资'] * 0.1
high_income_employees = df[df['工资'] > 10000]
```
PrettyTable 安装
```bash
pip install prettytable
```
创建表格:
```python
from prettytable import PrettyTable
table = PrettyTable()
table.add_column("姓名", ["张三", "李四", "王五"])
table.add_column("科目", ["数学", "语文", "英语"])
table.add_column("分数", [85, 90, 78])
print(table)
```
更多操作:
```python
table.align["姓名"] = "l" 左对齐
table.padding_width = 1 填充宽度
table.add_row(["赵一", "男", 20, 100000])
table.add_row(["钱二", "男", 21, 500])
print(table)
```
openpyxl 安装
```bash
pip install openpyxl
```
创建和编辑Excel文件:
```python
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws['A1'] = '姓名'
ws['B1'] = '年龄'
ws['C1'] = '性别'
ws['A2'] = '张三'
ws['B2'] = 20
ws['C2'] = '男'
ws['A3'] = '小红'
ws['B3'] = 17
ws['C3'] = '女'
wb.save('test.xlsx')
```
xlrd和xlwt 安装
```bash
pip install xlrd
pip install xlwt
```
读取和写入Excel文件:
```python
import xlrd
import xlwt
book = xlrd.open_workbook('test.xls')
sheet = book.sheet_by_index(0)
data = sheet.row_values(0)
print(data)
wb = xlwt.Workbook()
ws = wb.add_sheet('Sheet1')
ws.write(0, 0, '姓名')
ws.write(0, 1, '年龄')
ws.write(0, 2, '性别')
ws.write(1, 0, '张三')
ws.write(1, 1, 20)
ws.write(1, 2, '男')
wb.save('test.xls')
```
这些方法各有优缺点,选择哪个库或方法取决于你的具体需求,例如数据的规模、操作的复杂性以及对表格格式的要求。对于大多数情况, pandas和 PrettyTable是非常强大且易用的工具。