更新Pandas Dataframe时出现疑似无限循环问题求助
问题描述
我有一个包含section字段的DataFrame,部分行的section值为Concurrent Opinion - x(x为当前文档的相对索引,document是DataFrame的另一个字段)。需要将同一文档中,位于Concurrent Opinion - x之后、Concurrent Opinion - x+1之前的所有行的section字段值设为Concurrent Opinion - x。
我能筛选出全表中匹配Concurrent Opinion的行,但无法为中间的行设置目标值:尝试设置匹配行的section值时,代码一直运行却未挂起。我哪里出错了?
我的代码
concurrent_opinions_ids=paragraphs_df[paragraphs_df['section'].str.contains("Concurrent Opinion")].index for index in concurrent_opinions_ids: #get document_pos for paragraph curr_pos=paragraphs_df.loc[index, 'document_pos'].copy() curr_doc=paragraphs_df.loc[index, 'document'].copy() curr_section=paragraphs_df.loc[index, 'section'] paragraphs_indices=paragraphs_df[(paragraphs_df['document']==curr_doc) & (paragraphs_df['document_pos']>curr_pos)].index for ind in paragraphs_indices: #set section to current section paragraphs_df.loc[ind, 'section']=curr_section
最后一行paragraphs_df.loc[ind, 'section']=curr_section引发了问题。
我还尝试用curr_section=paragraphs_df.loc[index, 'section'].copy()获取值,以为是引用问题,但报错:'str' object has no attribute 'copy'
修改前的DataFrame
id document paragraph_id previous next length document_pos 4001 4001 16 187 186 188 35 55282 4002 4002 16 188 187 189 4 55317 4003 4003 16 189 188 190 86 55321 4004 4004 16 190 189 191 230 55407 4005 4005 16 191 190 192 1702 55637 4006 4006 16 192 191 193 154 57339 4007 4007 16 193 192 194 49 57493 4008 4008 16 194 193 195 720 57542 4009 4009 16 195 194 196 4 58262 4010 4010 16 196 195 197 232 58266 4011 4011 16 197 196 198 297 58498 4012 4012 16 198 197 199 36 58795 4013 4013 16 199 198 200 206 58831 4014 4014 16 200 199 201 42 59037 section function 4001 Decision Pending 4002 Decision Pending 4003 Concurrent Opinion - 1 Pending 4004 Decision Pending 4005 Decision Pending 4006 Decision Pending 4007 Decision Pending 4008 Decision Pending 4009 Decision Pending 4010 Decision Pending 4011 Decision Pending 4012 Decision Pending 4013 Decision Pending 4014 Decision Pending text 4001 NILSON PINILLA PINILLA Magistrado 4002 25 4003 SALVAMENTO DE VOTO DEL MAGISTRADO JORGE IVÁN ... 4004 PRINCIPIO DE OFICIOSIDAD Y DE PREVALENCIA DEL... 4005 Considero, sin embargo, que la argumentación ... 4006 FACULTAD OFICIOSA DEL JUEZ ADMINISTRATIVO-Jue... 4007 DERECHO PROCESAL-Finalidad (Salvamento de voto) 4008 La finalidad principal del derecho procesal y... 4009 27 4010 DERECHO DE ACCESO A LA ADMINISTRACION DE JUST... 4011 CONSTITUCIONALIZACION DEL DERECHO PROCESAL- O... 4012 Referencia: expediente T-3.407.509 4013 Acción de tutela instaurada por Tito Edmundo ... 4014 Magistrado Ponente: ALEXEI JULIO ESTRADA
预期修改后的DataFrame
id document paragraph_id previous next length document_pos 4001 4001 16 187 186 188 35 55282 4002 4002 16 188 187 189 4 55317 4003 4003 16 189 188 190 86 55321 4004 4004 16 190 189 191 230 55407 4005 4005 16 191 190 192 1702 55637 4006 4006 16 192 191 193 154 57339 4007 4007 16 193 192 194 49 57493 4008 4008 16 194 193 195 720 57542 4009 4009 16 195 194 196 4 58262 4010 4010 16 196 195 197 232 58266 4011 4011 16 197 196 198 297 58498 4012 4012 16 198 197 199 36 58795 4013 4013 16 199 198 200 206 58831 4014 4014 16 200 199 201 42 59037 section function 4001 Decision Pending 4002 Decision Pending 4003 Concurrent Opinion - 1 Pending 4004 Concurrent Opinion - 1 Pending 4005 Concurrent Opinion - 1 Pending 4006 Concurrent Opinion - 1 Pending 4007 Concurrent Opinion - 1 Pending 4008 Concurrent Opinion - 1 Pending 4009 Concurrent Opinion - 1 Pending 4010 Concurrent Opinion - 1 Pending 4011 Concurrent Opinion - 1 Pending 4012 Concurrent Opinion - 1 Pending 4013 Concurrent Opinion - 1 Pending 4014 Concurrent Opinion - 1 Pending text 4001 NILSON PINILLA PINILLA Magistrado 4002 25 4003 SALVAMENTO DE VOTO DEL MAGISTRADO JORGE IVÁN ... 4004 PRINCIPIO DE OFICIOSIDAD Y DE PREVALENCIA DEL... 4005 Considero, sin embargo, que la argumentación ... 4006 FACULTAD OFICIOSA DEL JUEZ ADMINISTRATIVO-Jue... 4007 DERECHO PROCESAL-Finalidad (Salvamento de voto) 4008 La finalidad principal del derecho procesal y... 4009 27 4010 DERECHO DE ACCESO A LA ADMINISTRACION DE JUST... 4011 CONSTITUCIONALIZACION DEL DERECHO PROCESAL- O... 4012 Referencia: expediente T-3.407.509 4013 Acción de tutela instaurada por Tito Edmundo ... 4014 Magistrado Ponente: ALEXEI JULIO ESTRADA
问题分析与解决方案
代码问题点
- 嵌套循环效率极低:两层逐行循环是Pandas中最耗时的操作之一,大DataFrame下会导致运行极慢,看起来像卡住但实际仍在执行。
- 未处理区间终止条件:代码会把当前
Concurrent Opinion之后的所有同文档行都设为该值,若文档中有多个Concurrent Opinion标记,后续标记会被覆盖。 - 不必要的copy操作:数值类型的
curr_pos、curr_doc无需copy();字符串类型的curr_section是不可变对象,调用copy()必然报错。
正确实现方法
利用Pandas的向量化操作和分组填充,高效完成需求:
import pandas as pd # 1. 创建临时列,仅保留Concurrent Opinion行的section值,其余设为NaN paragraphs_df['temp_section'] = paragraphs_df['section'].where( paragraphs_df['section'].str.contains('Concurrent Opinion') ) # 2. 按document分组,向前填充临时列的空值 paragraphs_df['temp_section'] = paragraphs_df.groupby('document')['temp_section'].ffill() # 3. 用填充后的临时列替换原始section,保留Concurrent Opinion之前的原始值 paragraphs_df['section'] = paragraphs_df['temp_section'].combine_first(paragraphs_df['section']) # 4. 删除临时列 paragraphs_df.drop('temp_section', axis=1, inplace=True)
代码解释
- 步骤1:
where方法筛选出目标行,非目标行设为空值,为后续填充做准备。 - 步骤2:按文档分组后用
ffill()(向前填充),让每个Concurrent Opinion之后的行继承该值,直到下一个Concurrent Opinion出现时自动替换。 - 步骤3:
combine_first优先使用填充后的临时列值,临时列为空的行(即Concurrent Opinion之前的行)保留原始section值。 - 步骤4:清理临时列,保持DataFrame结构整洁。
这种方法完全基于向量化操作,速度远快于循环,同时正确处理多Concurrent Opinion的区间划分。
内容的提问来源于stack exchange,提问作者k4runo
相关产品推荐
相关产品推荐

