近期调试程序,发现一简单的代码一直在运行,很长时间不终止,代码如下:
whole_df=pd.read_csv(r'./train.csv')
community=whole_df['COMMUNITY_ID'].unique()
for community_id in community:
temp=check_result[check_result['COMMUNITY_ID']==community_id]
start=temp.index.tolist()[0]
delanomaly_test(temp,start)
其中delanomaly_test 是对测试数据进行处理异常值的函数,函数里有对形参temp进行赋值的操作,而temp 是whole_df的切片,执行后,出现了很多提示:
/usr/local/python3/lib/python3.6/site-packages/pandas/core/indexing.py:1763: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
一大串的全是提示,而且还一直扩展向下,过了10分钟,不再出现提示,但是这段cell 执行符号里显示‘*’,为一直在执行,本身数据量不大,community 为200个,check_result为8万条,应该2、3分钟就结束了但是又过5分钟还是‘*’号,点‘Interrupt the kernel ’也是很长时间没反应。用写标准输出+写文件的方式测试下:
whole_df=pd.read_csv(r'./train.csv')
community=whole_df['COMMUNITY_ID'].unique()
filename='proeceeing.txt'
with open(file_name,'w+') as f:
f.write(file_name)
w=0 #进度的变量
for community_id in community:
if w%50==0:
print('w=%s' %str(w)) #打印至标准输出
f=open(file_name,'a')
f.write('\n '+str(w)+':')#写入文件
f.write(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
f.close()
temp=check_result[check_result['COMMUNITY_ID']==community_id]
start=temp.index.tolist()[0]
delanomaly_test(temp,start)
w=w+1
print('w=%s' %str(w)) #打印至标准输出
f=open(file_name,'a')
print('w=%s' %str(w))
f.write('\n '+str(w)+':') #写入文件
f.write(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
f.write('\n check_result executed ')
f.close()
执行后,文件内容如下:
processing.txt 0:2021-08-25 21:14:38 50:2021-08-25 21:14:43 100:2021-08-25 21:14:49 150:2021-08-25 21:14:54 200:2021-08-25 21:15:00 check_result executed
看来这段代码在一分钟之内已经执行完毕,再看标准输出,还是有很多之前的提示,同时标示进度的w值里,只发现了三条:
w=0
w=50
w=100
再向后就只有提示,再向后提示也终止了
因此这段代码一直执行的可能原因是短时间内写大量内容至标准输出,标准输出缓冲区满,无法打印提示和之后的内容,但程序实际已执行完毕。最后删除delanomaly_test 函数里的切片赋值语句,发现这段代码很快结束,至此问题有三个:切片不可直接赋值,标准输出不可靠,每个提示都要细看