python数据分析与可视化

提供一个基本的例子,使用Pandas进行数据处理,Matplotlib和Seaborn进行数据可视化。我们将使用一个虚构的数据集来演示这个过程。

首先,确保环境中已经安装了必要的库,如pandas, matplotlib, 和 seaborn。如果没有安装,可以通过pip安装它们:

bash 复制代码
pip install pandas matplotlib seaborn

接下来是一个简单的数据分析与可视化的Python脚本示例:

python 复制代码
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# 创建一个简单的数据集
data = {
    'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
    'Sales': [120, 150, 180, 160, 200],
    'Expenses': [80, 90, 110, 100, 130]
}

# 将数据转换为DataFrame
df = pd.DataFrame(data)

# 显示数据的前几行
print(df.head())

# 数据分析
# 计算利润
df['Profit'] = df['Sales'] - df['Expenses']
print("\nProfit calculation:\n", df)

# 数据可视化
plt.figure(figsize=(10, 5))

# 使用seaborn绘制折线图
sns.lineplot(x='Month', y='Sales', data=df, label='Sales')
sns.lineplot(x='Month', y='Expenses', data=df, label='Expenses')
sns.lineplot(x='Month', y='Profit', data=df, label='Profit')

# 添加图表标题和标签
plt.title('Monthly Sales, Expenses and Profit')
plt.xlabel('Month')
plt.ylabel('Amount ($)')
plt.legend()

# 显示图表
plt.show()

这段代码首先创建了一个简单的数据字典,并将其转换为一个Pandas DataFrame。然后计算每个月的利润,并将结果添加到DataFrame中。最后,它使用Matplotlib和Seaborn库来绘制每个月的销售额、支出和利润的折线图。

相关推荐
金銀銅鐵11 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1116 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0018 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵19 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf20 小时前
Agent 流程编排
后端·python·agent
copyer_xyf21 小时前
Agent RAG
后端·python·agent
copyer_xyf21 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf21 小时前
Agent 记忆管理
后端·python·agent
星云穿梭2 天前
用Python写一个带图形界面的学生管理系统——完整教程
python