Stata中调用Python的完整指南:从环境配置到代码实战解决数据处理效率难题

引言:Stata与Python的强强联合
在现代数据科学和计量经济学研究中,Stata和Python各自拥有独特的优势。Stata以其强大的统计分析功能、简洁的命令语法和严谨的计量方法著称,特别适合面板数据分析、因果推断和政策评估。而Python则在数据清洗、机器学习、网络爬虫和深度学习等领域表现出色,拥有丰富的第三方库和活跃的开发者社区。
将两者结合使用,可以充分发挥各自的优势:在Stata中完成专业的计量分析,同时利用Python处理复杂的数据预处理、文本分析或机器学习任务。本文将为您提供一份从零开始的完整指南,帮助您在Stata中无缝调用Python,解决数据处理效率难题。
第一部分:环境配置与安装
1.1 系统要求与准备工作
在开始之前,请确保您的系统满足以下要求:
Stata版本
:Stata 16或更高版本(Stata 15需要额外配置)
Python版本
:Python 3.7或更高版本(推荐3.8-3.10)
操作系统
:Windows、macOS或Linux均可
1.2 安装Python
如果您尚未安装Python,建议通过以下方式安装:
推荐方案:安装Anaconda/Miniconda
# 下载并安装Miniconda(轻量级)
# 访问 https://docs.conda.io/en/latest/miniconda.html

# 创建专门的Stata-Python环境
conda create -n stata_py python=3.9
conda activate stata_py

# 安装常用数据科学包
conda install numpy pandas scipy scikit-learn matplotlib seaborn
或直接安装Python官方版本
# Windows: 从 python.org 下载安装包
# macOS: 使用 Homebrew
brew install python@3.9

# 安装必要包
pip install numpy pandas scipy scikit-learn matplotlib seaborn
1.3 配置Stata识别Python路径
安装完成后,需要在Stata中配置Python路径:
* 方法1:临时设置(每次启动Stata后需要重新设置)
python set exec “C:\Users\YourName\anaconda3\envs\stata_py\python.exe” // Windows示例
python set exec “/Users/YourName/miniconda3/envs/stata_py/bin/python” // macOS/Linux示例

* 方法2:永久设置(推荐)
* 在Stata的profile.do文件中添加上述命令
* profile.do文件位置:
* Windows: C:\Users\YourName\ado\profile.do
* macOS: /Users/YourName/Library/Preferences/Stata/profile.do
验证配置是否成功
* 测试Python是否可用
python: import sys
python: print(sys.version)
python: print(“Hello from Python!”)
如果看到Python版本号和问候语,说明配置成功!
1.4 常见问题排查
问题1:Stata找不到Python
* 检查当前Python路径设置
python query exec

* 重新设置路径(确保路径指向Python可执行文件,不是目录)
python set exec “C:\path\to\python.exe”
问题2:Python包导入失败
* 在Python环境中测试包是否安装
python: import pandas as pd
python: print(pd.__version__)

* 如果失败,在命令行中重新安装
# conda install pandas
# pip install pandas
第二部分:Stata-Python交互基础语法
2.1 Python代码块语法
在Stata中调用Python代码有三种主要方式:
2.1.1 行内Python代码
* 使用 python: 前缀执行单行Python代码
python: import pandas as pd
python: import numpy as np
python: print(“当前时间:”, pd.Timestamp.now())
2.1.2 多行Python代码块
* 使用 python << EOF 和 EOF 包围多行代码 python << EOF import pandas as pd import numpy as np # 创建示例数据 data = { 'id': [1, 2, 3, 4, 5], 'value': [10, 20, 15, 25, 30], 'category': ['A', 'B', 'A', 'C', 'B'] } df = pd.DataFrame(data) print(df) EOF 2.1.3 交互式编程(推荐) * 使用 python 作为交互模式,可以跨多行执行 python import pandas as pd import numpy as np # 这里可以写多行代码,Stata会等待输入 # 按回车后继续输入,输入 end 结束 df = pd.DataFrame({'x': [1,2,3], 'y': [4,5,6]}) print(df) end 2.2 数据传递:Stata ↔ Python 2.2.1 从Stata传递数据到Python 方法1:使用stata.frame * 在Stata中准备数据 clear input id value category 1 10 "A" 2 20 "B" 3 15 "A" 4 25 "C" 5 30 "B" end * 将Stata数据加载到Python的stata.frame中 python import pandas as pd from sfi import Data # 获取当前Stata数据 stata_df = Data.get() print("从Stata获取的数据:") print(stata_df) print("\n数据形状:", stata_df.shape) print("列名:", stata_df.columns.tolist()) end 方法2:使用stata.frame作为桥梁 * 创建Stata数据框 frame create mydata frame change mydata clear input x y 1 4 2 5 3 6 end * 在Python中访问 python from sfi import Frame # 访问特定frame mydata = Frame("mydata") df = mydata.get() print(df) end 2.2.2 从Python传递数据到Stata 方法1:使用stata.frame返回数据 python import pandas as pd import numpy as np from sfi import Data # 创建新数据 df = pd.DataFrame({ 'id': np.arange(1, 11), 'value': np.random.normal(100, 15, 10), 'category': np.random.choice(['A', 'B', 'C'], 10) }) # 将数据写回Stata Data.add_obs(df.shape[0]) # 添加观测值 Data.set("id", df['id'].tolist()) Data.set("value", df['value'].tolist()) Data.set("category", df['category'].tolist()) print("数据已写回Stata") end * 查看结果 list 方法2:使用stata.frame创建新frame python import pandas as pd from sfi import Frame # 创建新数据框 df = pd.DataFrame({ 'x': [1, 2, 3, 4, 5], 'y': [2, 4, 6, 8, 10], 'z': [3, 6, 9, 12, 15] }) # 创建新frame new_frame = Frame("results") new_frame.set(df) print("数据已保存到Stata的results frame中") end * 切换到新frame查看 frame change results list 2.3 使用sfi模块(Stata Function Interface) sfi 是Stata提供的Python接口模块,包含三个核心类: 2.3.1 Data类:操作当前数据集 * 示例:数据清洗和转换 clear input id x y 1 1 4 2 2 5 3 3 6 4 . 7 5 5 8 end python from sfi import Data import numpy as np # 获取数据 df = Data.get() print("原始数据:") print(df) # 数据处理:填充缺失值 df['x'] = df['x'].fillna(df['x'].mean()) # 计算新变量 df['ratio'] = df['y'] / df['x'] # 写回Stata Data.set("x", df['x'].tolist()) Data.set("ratio", df['ratio'].tolist()) print("\n处理后的数据:") print(df) end * 查看结果 list 2.3.2 Frame类:操作特定数据框 * 创建多个数据框并操作 frame create sales frame change sales clear input year sales 2020 100 2021 120 2022 150 end python from sfi import Frame # 访问sales frame sales = Frame("sales") df = sales.get() # 计算增长率 df['growth'] = df['sales'].pct_change() * 100 # 写回 sales.set(df) print("增长率计算完成") end frame change sales list 2.3.3 Scalar类:传递标量值 * 在Stata和Python间传递单个值 scalar my_value = 123.456 python from sfi import Scalar # 从Stata读取标量 val = Scalar.getValue("my_value") print(f"从Stata读取的值: {val}") # 计算新值 new_val = val * 2 # 写回Stata Scalar.setValue("result", new_val) print(f"计算结果: {new_val},已保存到result标量") end display result 第三部分:实战案例——解决数据处理效率难题 3.1 案例1:大规模数据清洗与转换 场景 :处理包含100万条记录的销售数据,需要进行复杂的清洗和转换。 * 生成模拟大数据集(100万条记录) clear set obs 1000000 gen id = _n gen date = floor(runiform()*1000) gen sales = rnormal(1000, 200) gen product = rbinomial(1, 0.3) gen region = rint(1, 5) gen customer_id = rint(1, 10000) * 人为添加一些问题数据 replace sales = . if mod(id, 100) == 0 // 1%缺失 replace sales = -999 if mod(id, 200) == 0 // 异常值 replace product = . if mod(id, 50) == 0 // 2%缺失 save sales_data, replace 传统Stata方法(效率较低) * 传统Stata方法(处理时间较长) clear use sales_data * 数据清洗 drop if sales == . drop if sales < 0 replace sales = . if sales > 3000

* 数据转换
gen log_sales = log(sales)
gen sales_per_region = sales / region
gen date_format = date + 20000

* 分组统计
bysort region: egen mean_sales = mean(sales)
bysort region product: egen median_sales = median(sales)

* 保存结果
save cleaned_sales, replace
Python高效处理方法
* 使用Python加速处理(推荐)
clear
use sales_data

python
from sfi import Data
import pandas as pd
import numpy as np
import time

start_time = time.time()

# 获取数据
df = Data.get()
print(f”原始数据形状: {df.shape}”)

# 高效数据清洗
# 1. 删除缺失值
df = df.dropna(subset=[‘sales’])

# 2. 删除异常值(使用向量化操作)
df = df[df[‘sales’] >= 0]
df = df[df[‘sales’] <= 3000] # 3. 数据转换(使用NumPy向量化,比Pandas更快) df['log_sales'] = np.log(df['sales'].values) df['sales_per_region'] = df['sales'].values / df['region'].values df['date_format'] = df['date'].values + 20000 # 4. 分组统计(使用groupby) df['mean_sales'] = df.groupby('region')['sales'].transform('mean') df['median_sales'] = df.groupby(['region', 'product'])['sales'].transform('median') # 5. 处理缺失的product值(向前填充) df['product'] = df['product'].fillna(method='ffill') print(f"处理后数据形状: {df.shape}") print(f"处理时间: {time.time() - start_time:.2f}秒") # 写回Stata Data.drop_obs(Data.getObsTotal()) # 清空当前数据 Data.add_obs(df.shape[0]) # 添加新观测值 for col in df.columns: Data.set(col, df[col].tolist()) print("数据处理完成!") end * 保存结果 save cleaned_sales_py, replace 性能对比 : 传统Stata方法:约15-20秒 Python方法:约2-3秒(提升5-10倍) 3.2 案例2:复杂文本分析与自然语言处理 场景 :分析用户评论数据,进行情感分析和关键词提取。 * 创建模拟评论数据 clear set obs 1000 gen id = _n gen comment = "" gen rating = rint(1, 5) * 生成随机评论 forvalues i = 1/1000 { local words "good excellent bad terrible nice love hate amazing" local num_words = rint(3, 8) local comment_text = "" forvalues j = 1/`num_words' { local word = word("`words'", rint(1, 8)) local comment_text = "`comment_text' `word'" } replace comment = "`comment_text'" in `i' } save comments_data, replace Python实现文本分析 clear use comments_data python from sfi import Data import pandas as pd import numpy as np from textblob import TextBlob import re # 获取数据 df = Data.get() # 1. 文本清洗函数 def clean_text(text): if pd.isna(text): return "" # 转换为小写 text = text.lower() # 移除特殊字符 text = re.sub(r'[^\w\s]', '', text) return text.strip() # 2. 情感分析函数 def analyze_sentiment(text): if pd.isna(text) or text == "": return 0 blob = TextBlob(text) return blob.sentiment.polarity # 范围:-1到1 # 3. 关键词提取 def extract_keywords(text, top_n=3): if pd.isna(text) or text == "": return "" blob = TextBlob(text) words = [word for word in blob.words if len(word) > 2]
return ” “.join(words[:top_n])

# 应用处理
print(“开始文本分析…”)
df[‘clean_comment’] = df[‘comment’].apply(clean_text)
df[‘sentiment’] = df[‘comment’].apply(analyze_sentiment)
df[‘keywords’] = df[‘comment’].apply(extract_keywords)

# 创建评分标签
df[‘sentiment_label’] = pd.cut(df[‘sentiment’],
bins=[-1, -0.1, 0.1, 1],
labels=[‘Negative’, ‘Neutral’, ‘Positive’])

# 统计结果
print(“\n情感分布:”)
print(df[‘sentiment_label’].value_counts())

# 写回Stata
Data.set(“clean_comment”, df[‘clean_comment’].tolist())
Data.set(“sentiment”, df[‘sentiment’].tolist())
Data.set(“keywords”, df[‘keywords’].tolist())
Data.set(“sentiment_label”, df[‘sentiment_label’].tolist())

print(“\n文本分析完成!”)
end

* 查看结果
list id comment sentiment sentiment_label keywords in 1/10
3.3 案例3:机器学习模型集成
场景
:使用Python训练机器学习模型,预测客户流失,并将预测结果返回Stata。
* 创建模拟客户数据
clear
set obs 5000
gen id = _n
gen age = rnormal(35, 10)
gen tenure = runiformint(0, 60)
gen monthly_charges = rnormal(50, 20)
gen total_charges = tenure * monthly_charges
gen contract_type = runiformint(1, 3)
gen churn = rbinomial(1, 0.2) // 20%流失率

* 添加一些噪声
replace age = . if runiform() < 0.01 replace monthly_charges = monthly_charges * 1.5 if runiform() < 0.05 save customer_data, replace Python机器学习流程 clear use customer_data python from sfi import Data import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler from sklearn.metrics import classification_report, roc_auc_score import pickle # 获取数据 df = Data.get() print(f"原始数据形状: {df.shape}") # 1. 数据预处理 # 处理缺失值 imputer = SimpleImputer(strategy='median') features = ['age', 'tenure', 'monthly_charges', 'total_charges', 'contract_type'] df[features] = imputer.fit_transform(df[features]) # 标准化特征 scaler = StandardScaler() df[features] = scaler.fit_transform(df[features]) # 2. 划分训练测试集 X = df[features] y = df['churn'] X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y ) print(f"训练集: {X_train.shape}, 测试集: {X_test.shape}") # 3. 训练模型 model = RandomForestClassifier( n_estimators=100, max_depth=8, min_samples_split=20, random_state=42, class_weight='balanced' ) model.fit(X_train, y_train) # 4. 模型评估 y_pred = model.predict(X_test) y_pred_proba = model.predict_proba(X_test)[:, 1] print("\n模型评估报告:") print(classification_report(y_test, y_pred)) print(f"ROC AUC Score: {roc_auc_score(y_test, y_pred_proba):.4f}") # 5. 特征重要性 feature_importance = pd.DataFrame({ 'feature': features, 'importance': model.feature_importances_ }).sort_values('importance', ascending=False) print("\n特征重要性:") print(feature_importance) # 6. 预测所有客户的流失概率 df['churn_probability'] = model.predict_proba(X)[:, 1] df['churn_prediction'] = model.predict(X) # 7. 保存模型(可选) with open('churn_model.pkl', 'wb') as f: pickle.dump(model, f) with open('scaler.pkl', 'wb') as f: pickle.dump(scaler, f) with open('imputer.pkl', 'wb') as f: pickle.dump(imputer, f) print("\n模型训练完成!预测结果已写回Stata") # 写回Stata Data.set("churn_probability", df['churn_probability'].tolist()) Data.set("churn_prediction", df['churn_prediction'].tolist()) Data.set("age_imputed", df['age'].tolist()) Data.set("monthly_charges_imputed", df['monthly_charges'].tolist()) end * 查看预测结果 list id churn churn_probability churn_prediction in 1/10 * 分析预测结果 summarize churn_probability if churn == 1 summarize churn_probability if churn == 0 3.4 案例4:高级数据可视化 场景 :使用Python的Matplotlib/Seaborn生成复杂的统计图表,嵌入Stata报告。 * 创建销售数据 clear set obs 200 gen id = _n gen date = floor(runiform()*365) gen sales = 1000 + 5*date + rnormal(0, 100) gen region = rint(1, 4) gen product = rint(1, 3) * 添加季节性 replace sales = sales + 200*sin(2*_pi*date/365) save sales_viz, replace Python生成高级图表 clear use sales_viz python from sfi import Data import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import os # 获取数据 df = Data.get() # 设置中文字体(如果需要) plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # 创建图表 fig, axes = plt.subplots(2, 2, figsize=(14, 10)) fig.suptitle('销售数据分析报告', fontsize=16, fontweight='bold') # 1. 时间序列图 axes[0,0].plot(df['date'], df['sales'], alpha=0.7, color='steelblue') axes[0,0].set_title('销售时间序列') axes[0,0].set_xlabel('日期') axes[0,0].set_ylabel('销售额') axes[0,0].grid(True, alpha=0.3) # 2. 按区域的箱线图 sns.boxplot(data=df, x='region', y='sales', ax=axes[0,1]) axes[0,1].set_title('各区域销售分布') axes[0,1].set_xlabel('区域') axes[0,1].set_ylabel('销售额') # 3. 产品散点图 for product in df['product'].unique(): subset = df[df['product'] == product] axes[1,0].scatter(subset['date'], subset['sales'], label=f'产品{product}', alpha=0.6) axes[1,0].set_title('产品销售散点图') axes[1,0].set_xlabel('日期') axes[1,0].set_ylabel('销售额') axes[1,0].legend() # 4. 热力图(相关性) pivot_data = df.pivot_table(values='sales', index='region', columns='product', aggfunc='mean') sns.heatmap(pivot_data, annot=True, fmt='.0f', cmap='YlOrRd', ax=axes[1,1]) axes[1,1].set_title('区域-产品平均销售额热力图') plt.tight_layout() # 保存图表 output_dir = "C:/temp" // 修改为你的路径 if not os.path.exists(output_dir): os.makedirs(output_dir) output_path = os.path.join(output_dir, "sales_analysis.png") plt.savefig(output_path, dpi=300, bbox_inches='tight') print(f"图表已保存到: {output_path}") # 显示图表(在Stata中可能需要) plt.show() plt.close() end * 在Stata中显示图片(如果支持) display "请查看 C:/temp/sales_analysis.png" 第四部分:高级技巧与最佳实践 4.1 性能优化技巧 4.1.1 数据传输优化 * 避免频繁的数据传输 python from sfi import Data import pandas as pd import numpy as np import time # 不好的做法:多次传输 start = time.time() for i in range(10): df = Data.get() # 处理... Data.set("var" + str(i), df['x'].tolist()) print(f"多次传输耗时: {time.time() - start:.2f}秒") # 好的做法:一次性传输 start = time.time() df = Data.get() for i in range(10): df["var" + str(i)] = df['x'] * (i + 1) Data.set(df) print(f"单次传输耗时: {time.time() - start:.2f}秒") end 4.1.2 使用NumPy向量化 python from sfi import Data import pandas as pd import numpy as np import time df = Data.get() # 慢:使用Pandas循环 start = time.time() df['slow_result'] = 0 for i in range(len(df)): if df.loc[i, 'x'] > 0:
df.loc[i, ‘slow_result’] = np.log(df.loc[i, ‘x’])
print(f”Pandas循环: {time.time() – start:.4f}秒”)

# 快:使用NumPy向量化
start = time.time()
df[‘fast_result’] = np.where(df[‘x’] > 0, np.log(df[‘x’].values), 0)
print(f”NumPy向量化: {time.time() – start:.4f}秒”)

Data.set(df)
end
4.1.3 内存管理
python
from sfi import Data
import pandas as pd
import gc

# 处理大数据时,及时释放内存
df = Data.get()

# 处理…
df_processed = df.groupby(‘category’).agg({‘value’: [‘mean’, ‘sum’]})

# 写回需要的数据
Data.set(“mean_value”, df_processed[(‘value’, ‘mean’)].tolist())

# 删除大对象并强制垃圾回收
del df
del df_processed
gc.collect()

print(“内存已清理”)
end
4.2 错误处理与调试
4.2.1 完整的错误处理
python
from sfi import Data, Scalar
import pandas as pd
import traceback

try:
# 尝试获取数据
df = Data.get()

# 检查数据
if df.empty:
raise ValueError(“Stata数据集为空”)

# 尝试处理
df[‘result’] = df[‘x’] / df[‘y’]

# 写回
Data.set(“result”, df[‘result’].tolist())

# 设置成功标志
Scalar.setValue(“py_success”, 1)
Scalar.setValue(“py_error_msg”, “”)

except Exception as e:
# 记录错误信息
error_msg = str(e) + “\n” + traceback.format_exc()
print(f”Python错误: {error_msg}”)

# 写回Stata标量
Scalar.setValue(“py_success”, 0)
Scalar.setValue(“py_error_msg”, error_msg[:200]) # 限制长度

# 可以选择创建错误日志
with open(“python_error.log”, “a”) as f:
f.write(f”{pd.Timestamp.now()}: {error_msg}\n”)

end

* 在Stata中检查错误
if py_success == 0 {
display “Python处理失败”
display py_error_msg
}
else {
display “Python处理成功”
}
4.2.2 调试技巧
* 在Python代码中添加调试信息
python
from sfi import Data
import pandas as pd

# 打印数据信息
df = Data.get()
print(f”数据形状: {df.shape}”)
print(f”列名: {df.columns.tolist()}”)
print(f”数据类型:\n{df.dtypes}”)
print(f”缺失值:\n{df.isnull().sum()}”)

# 检查特定条件
if ‘x’ in df.columns and ‘y’ in df.columns:
print(f”x和y的相关性: {df[‘x’].corr(df[‘y’]):.4f}”)
else:
print(“错误:缺少必要列”)

end
4.3 项目组织与代码管理
4.3.1 创建Python模块
# 保存为 stata_utils.py
import pandas as pd
import numpy as np
from sfi import Data, Frame, Scalar

def clean_data(df):
“””数据清洗函数”””
df = df.copy()
# 处理缺失值
for col in df.select_dtypes(include=[np.number]).columns:
df[col] = df[col].fillna(df[col].median())
return df

def calculate_summary(df, group_var, value_var):
“””分组统计”””
summary = df.groupby(group_var)[value_var].agg([‘mean’, ‘median’, ‘std’, ‘count’])
return summary

def export_to_stata(df, frame_name=None):
“””导出到Stata”””
if frame_name:
frame = Frame(frame_name)
frame.set(df)
else:
Data.drop_obs(Data.getObsTotal())
Data.add_obs(df.shape[0])
for col in df.columns:
Data.set(col, df[col].tolist())
print(f”导出 {df.shape[0]} 行数据到Stata”)

# 在Stata中调用
python << EOF import sys sys.path.append("C:/path/to/your/scripts") # 添加模块路径 from stata_utils import clean_data, calculate_summary, export_to_stata from sfi import Data df = Data.get() # 使用模块函数 df_clean = clean_data(df) summary = calculate_summary(df_clean, 'region', 'sales') export_to_stata(summary, "sales_summary") EOF 4.3.2 使用配置文件 # config.py import os # 路径配置 DATA_PATH = "C:/data" OUTPUT_PATH = "C:/output" LOG_PATH = "C:/logs" # 模型参数 MODEL_PARAMS = { 'random_forest': { 'n_estimators': 100, 'max_depth': 8 }, 'logistic': { 'C': 1.0, 'max_iter': 1000 } } # 分析参数 ANALYSIS_CONFIG = { 'outlier_threshold': 3, 'missing_threshold': 0.3, 'correlation_threshold': 0.8 } 第五部分:常见问题与解决方案 5.1 环境配置问题 Q1: Stata找不到Python安装 * 解决方案:手动指定完整路径 python set exec "C:\Users\YourName\AppData\Local\Programs\Python\Python39\python.exe" * 或使用conda环境 python set exec "C:\Users\YourName\anaconda3\envs\stata_py\python.exe" Q2: Python包导入失败 * 在Stata中检查Python路径 python: import sys python: print(sys.executable) python: print(sys.path) * 确保包安装在正确的Python环境中 * 在命令行中: * conda activate stata_py * pip install pandas numpy 5.2 数据类型不匹配 Q3: Stata字符串与Python字符串编码问题 * Stata中的中文字符处理 clear input str20 name "张三" "李四" "王五" end python from sfi import Data df = Data.get() # 确保正确处理编码 df['name'] = df['name'].astype(str) print(df['name'].values) # 写回时确保编码正确 Data.set("name", df['name'].tolist()) end Q4: 缺失值处理差异 * Stata的缺失值(.)在Python中变为NaN clear input x y 1 2 3 . 5 6 end python from sfi import Data import numpy as np df = Data.get() print("原始数据:") print(df) # Python的NaN处理 df['y_filled'] = df['y'].fillna(0) # 写回Stata(NaN会自动转为缺失值) Data.set("y_filled", df['y_filled'].tolist()) print("\n处理后:") print(df) end list 5.3 性能问题 Q5: 大数据传输慢 * 解决方案:分块处理 python from sfi import Data import pandas as pd # 分块读取和处理 chunk_size = 10000 total_rows = Data.getObsTotal() for start in range(0, total_rows, chunk_size): end = min(start + chunk_size, total_rows) # 只获取当前块 df_chunk = Data.get(start+1, end) # Stata索引从1开始 # 处理当前块 df_chunk['processed'] = df_chunk['x'] * 2 # 写回(需要累积结果) if start == 0: result = df_chunk else: result = pd.concat([result, df_chunk]) # 最终写回 Data.set("processed", result['processed'].tolist()) end 5.4 版本兼容性 Q6: Stata 15与Stata 16+的差异 * Stata 15需要额外配置 * 确保Python版本为3.7或更低 * 使用旧版sfi模块(如果可用) * Stata 16+支持更好的Python集成 * 推荐使用Python 3.8+ 第六部分:完整工作流示例 6.1 端到端数据科学项目 * ============================================================ * 项目:客户流失预测分析 * 作者:Your Name * 日期:2024 * ============================================================ * 1. 数据准备 clear cd "C:/projects/churn_prediction" use raw_customer_data.dta, replace * 2. 数据概览 describe summarize * 3. 调用Python进行高级分析 python << EOF from sfi import Data, Scalar import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report, roc_auc_score import pickle import json import os # 配置 config = { 'test_size': 0.2, 'random_state': 42, 'model_params': { 'n_estimators': 100, 'max_depth': 8, 'random_state': 42 } } # 获取数据 df = Data.get() print(f"数据加载: {df.shape}") # 数据预处理 # 1. 处理缺失值 numeric_cols = df.select_dtypes(include=[np.number]).columns df[numeric_cols] = df[numeric_cols].fillna(df[numeric_cols].median()) # 2. 特征工程 df['tenure_group'] = pd.cut(df['tenure'], bins=[0, 12, 24, 48, 100], labels=['New', 'Medium', 'Long', 'Very_Long']) df['monthly_to_total'] = df['monthly_charges'] / (df['total_charges'] + 1) # 3. 准备建模数据 features = ['age', 'tenure', 'monthly_charges', 'total_charges', 'contract_type', 'monthly_to_total'] X = pd.get_dummies(df[features + ['tenure_group']], drop_first=True) y = df['churn'] # 4. 划分数据集 X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=config['test_size'], random_state=config['random_state'], stratify=y ) # 5. 训练模型 model = RandomForestClassifier(**config['model_params']) model.fit(X_train, y_train) # 6. 评估 y_pred = model.predict(X_test) y_pred_proba = model.predict_proba(X_test)[:, 1] # 7. 保存结果 results = { 'accuracy': float(np.mean(y_pred == y_test)), 'roc_auc': float(roc_auc_score(y_test, y_pred_proba)), 'feature_importance': dict(zip(X.columns, model.feature_importances_)), 'config': config } # 保存到文件 with open('model_results.json', 'w') as f: json.dump(results, f, indent=2) # 保存模型 with open('churn_model.pkl', 'wb') as f: pickle.dump(model, f) # 写回预测结果 df['churn_probability'] = model.predict_proba(X)[:, 1] df['churn_prediction'] = model.predict(X) # 写回Stata Data.set("churn_probability", df['churn_probability'].tolist()) Data.set("churn_prediction", df['churn_prediction'].tolist()) # 保存关键指标到Stata标量 Scalar.setValue("model_accuracy", results['accuracy']) Scalar.setValue("model_auc", results['roc_auc']) Scalar.setValue("py_success", 1) print("分析完成!") EOF * 4. 结果展示 if py_success == 1 { display "模型性能指标" display "准确率: " %9.4f model_accuracy display "AUC: " %9.4f model_auc * 查看预测结果 list id churn churn_probability churn_prediction in 1/20 * 保存最终数据 save churn_predictions.dta, replace * 生成报告 python << EOF import json with open('model_results.json', 'r') as f: results = json.load(f) print("\n=== 模型报告 ===") print(f"准确率: {results['accuracy']:.4f}") print(f"AUC: {results['roc_auc']:.4f}") print("\n特征重要性排序:") for feat, imp in sorted(results['feature_importance'].items(), key=lambda x: x[1], reverse=True)[:5]: print(f" {feat}: {imp:.4f}") EOF } else { display "Python分析失败,请检查错误信息" } 结论 Stata与Python的结合为数据分析师和研究人员提供了强大的工具组合。通过本文的指南,您应该已经掌握了: 环境配置 :正确安装和配置Python环境,确保Stata能够调用 基础语法 :掌握Stata-Python交互的核心语法和数据传递方法 实战应用 :通过四个实际案例,学习如何解决复杂的数据处理问题 高级技巧 :性能优化、错误处理和项目组织的最佳实践 问题解决 :常见问题的诊断和解决方案 关键要点总结 : 性能提升 :对于大数据处理,Python通常比纯Stata快5-10倍 功能扩展 :Python提供了Stata不具备的机器学习、NLP和深度学习能力 工作流整合 :可以在Stata中无缝集成Python代码,保持原有工作流程 可重复性 :通过脚本化,确保分析过程可重复、可验证 下一步建议 : 从简单的数据清洗任务开始练习 逐步尝试机器学习模型集成 建立自己的Python-Stata工具库 关注Stata和Python的更新,及时调整代码 通过不断实践,您将能够充分利用这两个强大工具的优势,显著提升数据分析效率和研究质量。