Debian系统下使用Python进行数据分析的完整流程

Debian系统默认仓库包含Python3,首先更新系统包列表并安装Python3及pip(Python包管理工具):
sudo apt update && sudo apt upgrade -y# 更新系统sudo apt install python3 python3-pip -y# 安装Python3和pip验证安装:
python3 --version# 查看Python版本(建议3.6+)pip3 --version # 查看pip版本使用pip安装Python数据分析的核心库,覆盖数据处理、数值计算、可视化及机器学习:
pip3 install pandas numpy matplotlib seaborn scikit-learn scipy statsmodels jupyterlab -y通过pandas读取常见数据源(如CSV、Excel、SQL数据库):
import pandas as pd# 读取CSV文件data = pd.read_csv('data.csv')# 读取Excel文件# data = pd.read_excel('data.xlsx')# 查看数据前5行print(data.head())处理数据中的缺失值、重复值、异常值及格式问题:
# 检查缺失值print(data.isnull().sum())# 删除含缺失值的行data.dropna(inplace=True)# 填充缺失值(如用均值填充'Age'列)# data['Age'].fillna(data['Age'].mean(), inplace=True)# 删除重复值data.drop_duplicates(inplace=True)# 转换数据类型(如将'Price'列转为整数)# data['Price'] = data['Price'].astype(int)# 处理异常值(如删除'Age'列中超过120的值)# data = data[data['Age'] <= 120]通过统计分析与可视化了解数据特征:
# 描述性统计(计算均值、标准差、分位数等)desc_stats = data.describe()print(desc_stats)# 分组聚合(如按'Category'列计算销售额均值)group_stats = data.groupby('Category')['Sales'].mean()print(group_stats)# 相关性分析(计算数值列的相关系数矩阵)corr_matrix = data.corr()print(corr_matrix)# 数据可视化(直方图:展示'Age'分布)import matplotlib.pyplot as pltimport seaborn as snsplt.figure(figsize=(10, 6))sns.histplot(data['Age'], bins=20, kde=True)plt.title('Age Distribution')plt.xlabel('Age')plt.ylabel('Frequency')plt.show()# 箱线图:展示不同'Species'的'Petal Length'分布sns.boxplot(x='Species', y='Petal_Length', data=iris)plt.title('Petal Length by Species')plt.show()使用scikit-learn构建简单的线性回归模型(以预测房价为例):
from sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_squared_error, r2_score# 准备特征(X)与目标变量(y)X = data[['Size', 'Bedrooms']]# 特征列y = data['Price']# 目标列# 划分训练集与测试集(80%训练,20%测试)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# 初始化模型model = LinearRegression()# 训练模型model.fit(X_train, y_train)# 预测测试集y_pred = model.predict(X_test)# 评估模型mse = mean_squared_error(y_test, y_pred)r2 = r2_score(y_test, y_pred)print(f'Mean Squared Error: {mse:.2f}')print(f'R^2 Score: {r2:.2f}')通过可视化或报告呈现分析结论:
# 导出清洗后的数据data.to_csv('cleaned_data.csv', index=False)# 导出分析结果(如描述性统计)desc_stats.to_excel('desc_stats.xlsx')python3 -m venv myenv# 创建虚拟环境source myenv/bin/activate# 激活虚拟环境(Debian/Ubuntu)pip install pandas numpy matplotlib seaborn scikit-learn jupyterlab# 在虚拟环境中安装库jupyter lab# 启动Jupyter Lab(默认端口8888)pip3 install --upgrade pandas numpy matplotlib seaborn scikit-learn通过以上步骤,可在Debian系统上完成从数据收集到建模的全流程数据分析任务。根据具体需求,可扩展使用其他库(如TensorFlow/PyTorch用于深度学习、NLTK用于自然语言处理)。