如何将Azure文本情感分析API结果存入Pandas DataFrame新列
Azure情感分析API对接Pandas DataFrame实现方案
报错原因
直接传入df['column_name']会报错是因为Azure接口接收的是纯字符串列表,而pandas的Series对象直接传入会存在类型不兼容问题,同时如果列里有空值、超长文本也会触发接口报错。
完整实现代码
import pandas as pd from azure.core.credentials import AzureKeyCredential from azure.ai.textanalytics import TextAnalyticsClient # 初始化客户端 credential = AzureKeyCredential("<api_key>") endpoint="https://<region>.api.cognitive.microsoft.com/" text_analytics_client = TextAnalyticsClient(endpoint, credential) # 替换为你自己的DataFrame读取逻辑 # df = pd.read_csv("你的数据文件路径.csv") text_column = "需要分析的文本列名" # 替换为实际的列名 # 预处理:过滤空值,保留原始索引避免结果错位 valid_df = df[df[text_column].notna()].copy() documents = valid_df[text_column].tolist() # 按接口限制分批调用,单次调用最多支持10条文本 batch_size = 10 all_results = [] for i in range(0, len(documents), batch_size): batch = documents[i:i+batch_size] response = text_analytics_client.analyze_sentiment(batch, language="en") for doc in response: if not doc.is_error: all_results.append({ "sentiment": doc.sentiment, "positive_score": doc.confidence_scores.positive, "neutral_score": doc.confidence_scores.neutral, "negative_score": doc.confidence_scores.negative }) else: # 异常结果填充空值 all_results.append({ "sentiment": None, "positive_score": None, "neutral_score": None, "negative_score": None }) # 结果回填到原DataFrame result_df = pd.DataFrame(all_results, index=valid_df.index) df = df.join(result_df)
补充说明
- 单条文本长度不能超过5120个字符,超出限制的文本需要提前截断处理
- 如果不需要置信度得分,可简化结果处理逻辑,仅保留
sentiment字段即可
内容的提问来源于stack exchange,提问作者César Castor
相关产品推荐
相关产品推荐

