You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法将Reddit评论与帖子数据写入Pandas DataFrame的问题及解决

解决Reddit机器人评论数据存入Pandas DataFrame的问题

问题场景

开发Reddit机器人用于监测含关键词creosote的评论并发送邮件通知,但无法将多条匹配的帖子/评论数据正确存入Pandas DataFrame:使用索引赋值仅能保留首行数据,调整索引后问题依旧。

错误代码(原实现)

import pandas as pd
import praw

# 初始化Reddit客户端(配置省略)
reddit = praw.Reddit(client_id="YOUR_ID", client_secret="YOUR_SECRET", user_agent="YOUR_AGENT")

# 初始化空DataFrame
df = pd.DataFrame(columns=['post_title', 'comment_body', 'comment_url'])

# 流式获取评论
for comment in reddit.subreddit('all').stream.comments():
    if 'creosote' in comment.body.lower():
        # 尝试通过索引赋值存储数据
        df.loc[0] = [comment.submission.title, comment.body, comment.permalink]
        # 邮件通知逻辑(省略)

问题原因

每次匹配到目标评论时,df.loc[0]会直接覆盖第0行的原有数据,导致最终DataFrame永远只保留最后一次匹配的结果;即使尝试用len(df)作为索引,也可能因Pandas对动态索引的处理特性,无法稳定追加新行。

修正方案:使用df.append()追加数据

通过df.append()方法将单条匹配数据构造为Series或DataFrame后,追加到原DataFrame中,并设置ignore_index=True自动更新索引。

正确代码(修正后)

import pandas as pd
import praw

reddit = praw.Reddit(client_id="YOUR_ID", client_secret="YOUR_SECRET", user_agent="YOUR_AGENT")

df = pd.DataFrame(columns=['post_title', 'comment_body', 'comment_url'])

for comment in reddit.subreddit('all').stream.comments():
    if 'creosote' in comment.body.lower():
        # 构造单条数据的Series
        new_comment_data = pd.Series({
            'post_title': comment.submission.title,
            'comment_body': comment.body,
            'comment_url': comment.permalink
        })
        # 追加到DataFrame并重置索引
        df = df.append(new_comment_data, ignore_index=True)
        # 邮件通知逻辑(省略)

兼容Pandas 2.0+的替代方案

若使用Pandas 2.0及以上版本,append()方法已被弃用,推荐使用pd.concat()实现追加:

# 构造单条数据的DataFrame
new_comment_df = pd.DataFrame([{
    'post_title': comment.submission.title,
    'comment_body': comment.body,
    'comment_url': comment.permalink
}])
# 合并到原DataFrame
df = pd.concat([df, new_comment_df], ignore_index=True)

内容的提问来源于stack exchange,提问作者Squirrel King

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 09:26:14