pandas处理excel数据

一、写入excel数据

python 复制代码
# 方法二:使用 pandas(适合大量结构化数据)----数据是列表、字典、DataFrame 等结构化格式
import pandas  as pd
# 1. 准备数据(可以是列表、字典、DataFrame等)
data = {
    "姓名": ["张三", "李四", "王五"],
    "语文": [95, 88, 91],
    "数学": [90, 92, 87]
}

# 2. 将数据转换为DataFrame(pandas的核心数据结构)
df = pd.DataFrame(data)
print(df)

# 3. 写入Excel文件
# index=False 表示不写入行索引(避免多余的一列)
df.to_excel("学生成绩_pandas.xlsx", sheet_name="学生成绩表", index=False)
print("数据写入Excel成功!")

二、读取excel数据

python 复制代码
import pandas as pd

# 1. 读取Excel文件(核心方法)
# 读取指定工作表,header=0 表示第一行作为列名(默认)
df = pd.read_excel("学生成绩.xlsx", sheet_name="学生成绩表",  header=0)
print("=== 读取的完整数据 ===")
print(df)
# === 读取的完整数据 ===
#    姓名  语文  数学
# 0  张三  95  90
# 1  李四  88  92
# 2  王五  91  87

print("\n=== 读取指定列 ===")
# 读取"姓名"列
names = df["姓名"]
print(names)
# === 读取指定列 ===
# 0    张三
# 1    李四
# 2    王五

print("\n=== 读取指定行 ===")
# 读取第2行(索引从0开始,对应Excel的第3行:李四)
# iloc:按「行索引+列索引」
row2 = df.iloc[1]
print(row2)
# === 读取指定行 ===
# 姓名    李四
# 语文    88
# 数学    92

print("\n=== 读取指定单元格 ===")
# 读取"李四"的数学成绩(行索引1,列名"数学"---可选参数)
# loc:按「行标签+列名」
math_score = df.loc[1, "数学"]
print("李四的数学成绩:", math_score)  # 输出:92
# === 读取指定单元格 ===
# 李四的数学成绩: 92
chinese_score = df.loc[1]
print(chinese_score)



print("\n=== 筛选数据 ===")
# 筛选语文成绩大于90分的行(pandas的优势:便捷的数据分析)
high_chinese = df[df["语文"] > 90]
print("语文成绩大于90分的学生:")
print(high_chinese)
# 语文成绩大于90分的学生:
#    姓名  语文  数学
# 0  张三  95  90
# 2  王五  91  87

三、excel表格追加行内容

python 复制代码
import pandas as pd

# 1. 定义Excel文件路径和新数据
excel_path = "学生成绩.xlsx"
new_data = {
    "姓名": ["孙八", "周九"],
    "语文": [78, 90],
    "数学": [96, 82]
}

# 2. 将数据转换为DataFrame(pandas的核心数据结构)
new_df = pd.DataFrame(new_data)
print(new_df)

with pd.ExcelWriter(
    excel_path,
    mode="a",
    engine="openpyxl", # 必须指定openpyxl引擎(支持.xlsx追加)
    if_sheet_exists="overlay"  # 工作表存在时,覆盖(实际是追加到末尾)
) as writer:
    # 获取原有数据的行数(用于定位新数据的起始行)
    try:
        # 读取原有工作表,获取行数
        old_df = pd.read_excel(excel_path, sheet_name="学生成绩表")
        startrow = len(old_df)+1  # 新数据从原有数据的下一行开始
    except:
        startrow = 0  # 若工作表不存在,从第0行开始(即新建工作表)

    # 写入新数据(header=False 表示不重复写入表头)
    new_df.to_excel(
        writer,
        sheet_name="学生成绩表",
        index=False,
        header=False,  # 已有表头,无需重复写入
        startrow=startrow  # 指定新数据的起始行
    )
print("新数据已高效追加写入Excel!")

四、excel表格追加列内容

1、批量追加列数据

python 复制代码
import os.path

import pandas as pd

excel_path = "学生成绩.xlsx"
if os.path.exists(excel_path):
    df = pd.read_excel(excel_path, sheet_name="学生成绩表")

    # 1. 定义要新增的多列数据(字典形式,键=列名,值=列数据)
    new_columns = {
        "英语": [88, 92, 85, 80, 95],
        "班级": "一班",  # 固定值列
        "排名": [1, 3, 2, 5, 4]
    }
    # print(new_columns.items())   # [('英语', [88, 92, 85, 80, 95]), ('班级', '一班'), ('排名', [1, 3, 2, 5, 4])

    # 2. 批量新增列
    dict_data = []
    for col_name,col_data in new_columns.items():
        df[col_name] = col_data

    # 3. 写入Excel
    df.to_excel(excel_path, sheet_name="学生成绩表", index=False)
    print("多列数据追加成功!")
    print(df)
else:
    print("文件不存在!")

2、追加指定的列数据

python 复制代码
import os.path

import pandas as pd

excel_path = "学生成绩.xlsx"
if os.path.exists(excel_path):
    df = pd.read_excel(excel_path, sheet_name="学生成绩表")
    df.insert(loc=6, column="地理", value=[88, 92, 85, 80, 95])

    
    # 3. 写入Excel index=False  禁止将 pandas DataFrame 的行索引写入 Excel 文件禁止将 pandas DataFrame 的行索引写入 Excel 文件
    df.to_excel(excel_path, sheet_name="学生成绩表", index=False)
    print("多列数据追加成功!")
    print(df)
else:
    print("文件不存在!")
相关推荐
wregjru2 小时前
【操作系统】3.开发工具
excel
wtsolutions5 小时前
MCP Service Integration - Excel to JSON for AI and Automation
人工智能·json·excel
智航GIS15 小时前
11.11 Pandas性能革命:向量化操作与内存优化实战指南
python·pandas
wtsolutions15 小时前
JSON to Excel Add-in - Seamless Integration Within Excel
json·excel
wtsolutions16 小时前
Getting Started with JSON to Excel Web App - Convert in Seconds
json·excel·web app
wtsolutions19 小时前
Using the JSON to Excel API - Programmatic Access for Developers
json·excel
qq_4351395720 小时前
EasyExcel(FastExcel)Excel导出功能 技术文档
excel
百锦再20 小时前
python之路并不一马平川:带你踩坑Pandas
开发语言·python·pandas·pip·requests·tools·mircro
wtsolutions1 天前
Understanding JSON Formats - What JSON to Excel Supports
json·excel