如何基于条件创建Pandas列,统计论坛线程的帖子总数?
实现步骤
假设你的DataFrame名为df,可以通过以下代码完成目标列的创建:
先计算每个线程的总帖子数
利用thread_name分组,提取post_number的最大值(因为post_number是线程内的顺序编号,最大值就是该线程的总帖子数):thread_totals = df.groupby('thread_name')['post_number'].max().reset_index(name='total_posts')合并总帖子数到原DataFrame
通过关联操作把计算结果匹配回原数据:df = df.merge(thread_totals, on='thread_name', how='left')生成目标列并清理临时数据
根据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_name | thread_name | post_text | post_number | thread_opening | thread_comments_count |
|---|---|---|---|---|---|
| BoxCutter | It's Okay When We Do It. | ..... | 1 | 1 | 3 |
| Docket_33 | It's Okay When We Do It. | ..... | 2 | 0 | 0 |
| Hearmeout | It's Okay When We Do It. | ..... | 3 | 0 | 0 |
| yez | Science | ..... | 1 | 1 | 4 |
| Mainländer | Science | ..... | 2 | 0 | 0 |
| 400z | Science | ..... | 3 | 0 | 0 |
| Farnham | Science | ..... | 4 | 0 | 0 |
内容的提问来源于stack exchange,提问作者Connor95
相关产品推荐
相关产品推荐

