[ PROMPT_NODE_25732 ]
Excel Analysis
[ SKILL_DOCUMENTATION ]
# Excel 分析
## 快速开始
使用 pandas 读取 Excel 文件:
python
import pandas as pd
# 读取 Excel 文件
df = pd.read_excel("data.xlsx", sheet_name="Sheet1")
# 显示前几行
print(df.head())
# 基本统计信息
print(df.describe())
## 读取多个工作表
处理工作簿中的所有工作表:
python
import pandas as pd
# 读取所有工作表
excel_file = pd.ExcelFile("workbook.xlsx")
for sheet_name in excel_file.sheet_names:
df = pd.read_excel(excel_file, sheet_name=sheet_name)
print(f"n{sheet_name}:")
print(df.head())
## 数据分析
执行常见分析任务:
python
import pandas as pd
df = pd.read_excel("sales.xlsx")
# 分组并聚合
sales_by_region = df.groupby("region")["sales"].sum()
print(sales_by_region)
# 筛选数据
high_sales = df[df["sales"] > 10000]
# 计算指标
df["profit_margin"] = (df["revenue"] - df["cost"]) / df["revenue"]
# 按列排序
df_sorted = df.sort_values("sales", ascending=False)
## 创建 Excel 文件
将数据写入带有格式的 Excel:
python
import pandas as pd
df = pd.DataFrame({
"Product": ["A", "B", "C"],
"Sales": [100, 200, 150],
"Profit": [20, 40, 30]
})
# 写入 Excel
writer = pd.ExcelWriter("output.xlsx", engine="openpyxl")
df.to_excel(writer, sheet_name="Sales", index=False)
# 获取工作表以进行格式化
worksheet = writer.sheets["Sales"]
# 自动调整列宽
for column in worksheet.columns:
max_length = 0
column_letter = column[0].column_letter
for cell in column:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
worksheet.column_dimensions[column_letter].width = max_length + 2
writer.close()
## 数据透视表
以编程方式创建数据透视表:
python
import pandas as pd
df = pd.read_excel("sales_data.xlsx")
# 创建数据透视表
pivot = pd.pivot_table(
df,
values="sales",
index="region",
columns="product",
aggfunc="sum",
fill_value=0
)
print(pivot)
# 保存数据透视表
pivot.to_excel("pivot_report.xlsx")
## 图表和可视化
从 Excel 数据生成图表:
python
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_excel("data.xlsx")
# 创建柱状图
df.plot(x="category", y="value", kind="bar")
plt.title("按类别销售额")
plt.xlabel("类别")
plt.ylabel("销售额")
plt.tight_layout()
plt.savefig("chart.png")
# 创建饼图
df.set_index("category")["value"].plot(kind="pie"