import pandas as pd
import openpyxl
# DataFrame 基本操作
# read DataFrame from excel
df = pd.read_excel('202201报表.xlsx')
print(type(df))
print(df)
# 指定worksheet的名称,读入数据表
df = pd.read_excel('202201报表.xlsx', sheet_name="客户")
print(df)
# df.columns 是一个 Series 对象
print(df.columns)
# 显示每一列的名称
for i in range(len(df.columns)):
print(df.columns[i])
# 如果存在名为"城市"的列
if '城市' in df.columns:
column = df['城市'] # 取得名为"城市"的一列
print(type(column)) # column 是一个 Series 对象
print(column)
print(column[0]) # 取得 columns 第1个数据(索引号从0开始)
print(column.to_list()) # 将series转换为 list
# 取得一行 (Series)
if len(df) > 0:
row = df.iloc[0] # 取得第一行(从0开始)
print(type(row)) # row 是一个 Series 对象
print(row)
print(row['城市']) # 取得该行中 列名为"城市"的单元格的值
# 取得一个格子的值
print(df.loc[1, '城市'])
# 写入一个格子的值
df.loc[1, '城市'] = "新城"
print(df.loc[1, '城市'])
# 取得 金额列的 最大、最小、平均值
print(df['金额'].max(), df['金额'].min(), df['金额'].mean())
print(len(df)) # len(df)取得行数
print(len(df.columns)) # len(df.columns)取得列数
# 将DataFrame存入excel文件(注意:直接使用 to_excel() 将会丢弃原excel文件中的其他worksheet)
filename = '新报表.xlsx'
df.to_excel(filename, sheet_name="商品销售")
def save_to_exist_excel(df, filename, sheet_name, index=False, startrow=0, startcol=0, **kwargs):
"""
将DataFrame存入已有的excel文件
:param df: DataFrame 对象
:param filename: Excel 文件名
:param sheet_name: 工作表名称(标题)
:param index: (可选)索引列是否保存
:param startrow: (可选)开始写入的行号, 第一行为0, 第二行为1, ...
:param startcol: (可选)开始写入的列号, A列为0, B列为1 ...
:param kwargs: (可选)其他参数
:return: None
"""
book = openpyxl.load_workbook(filename)
writer = pd.ExcelWriter(filename, engine='openpyxl')
writer.book = book
writer.sheets = {}
for ws in book.worksheets:
writer.sheets[ws.title] = ws
df.to_excel(writer, sheet_name=sheet_name, index=index, startcol=0, startrow=0, **kwargs)
writer.save()
# 读出数据
filename = '202201报表.xlsx'
df = pd.read_excel('202201报表.xlsx', sheet_name="商品销售")
df.loc[1, '城市'] = "新城" # 修改单元格
# 将DataFrame存入已存在的excel文件
save_to_exist_excel(df, filename, sheet_name="商品销售")
# Pandas Official Document Introduction:
# https://pandas.pydata.org/pandas-docs/stable/getting_started/intro_tutorials/index.html
没有合适的资源?快使用搜索试试~ 我知道了~
Python 自动化教程(2) : Excel自动化:使用pandas库,相关源码和文件
共9个文件
py:7个
csv:1个
xlsx:1个
需积分: 50 8 下载量 169 浏览量
2022-07-31
17:43:12
上传
评论
收藏 18KB ZIP 举报
温馨提示
Python 自动化教程(2) : Excel自动化:使用pandas库,相关源码和文件
资源详情
资源评论
资源推荐
收起资源包目录
第二篇Excel自动化_使用pandas库.zip (9个子文件)
study_pandas2.py 2KB
study_pandas3.py 879B
study_pandas6.py 1KB
study_pandas4.py 737B
202201.csv 171B
study_pandas5.py 705B
read_excel_with_row_col.py 2KB
202201报表.xlsx 16KB
study_pandas1.py 3KB
共 9 条
- 1
JoStudio
- 粉丝: 1066
- 资源: 28
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论0