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

如何基于条件创建Pandas列,统计论坛线程的帖子总数?

实现步骤

假设你的DataFrame名为df,可以通过以下代码完成目标列的创建:

  1. 先计算每个线程的总帖子数
    利用thread_name分组,提取post_number的最大值(因为post_number是线程内的顺序编号,最大值就是该线程的总帖子数):

    thread_totals = df.groupby('thread_name')['post_number'].max().reset_index(name='total_posts')
    
  2. 合并总帖子数到原DataFrame
    通过关联操作把计算结果匹配回原数据:

    df = df.merge(thread_totals, on='thread_name', how='left')
    
  3. 生成目标列并清理临时数据
    根据thread_opening的值设置列内容,最后删除临时列:

    df['thread_comments_count'] = df.apply(lambda row: row['total_posts'] if row['thread_opening'] == 1 else 0, axis=1)
    df.drop('total_posts', axis=1, inplace=True)
    

处理后的数据示例

user_namethread_namepost_textpost_numberthread_openingthread_comments_count
BoxCutterIt's Okay When We Do It......113
Docket_33It's Okay When We Do It......200
HearmeoutIt's Okay When We Do It......300
yezScience.....114
MainländerScience.....200
400zScience.....300
FarnhamScience.....400

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 09:35:33