Python处理百万条csv或excel数据,提高效率np.where用法

最近在工作中遇到一个问题:需要对200万条csv数据进行清洗判断,考虑到在hive中不好操作循环,数据是从hive上下载下来的,然后考虑用python解决:

数据处理需要先对行数做判断,然后根据该行某一列的数据值跟200作比较再判断取值,涉及到后面的值会取到前面一行的值。

原来程序是这样:

for i in data1.index:
    if i % 9 == 0:
        data1['wo_new'].loc[i] = data1['wo_id'].loc[i] if data1['dis1'].loc[i] >= 200 else data1['wo_new'].loc[i]
    else:
        data1['wo_new'].loc[i] = data1['wo_id'].loc[i] if data1['dis1'].loc[i] >= 200 else data1['wo_new'].loc[i-1]

结果处理200万左右的数据量非常卡,程序运行了一下午也没有跑出来,对于这样的百万数据,循环遍历是非常耗时的,后来询问大神得知可以考虑使用np.where,用了np.where嵌套,终于解决了这个问题:

for i in range(0,9):
    data1['wo_new']=np.where((data1['dis1']>= 200)&(data1.index%9==0),data1['wo_id'],np.where((data1['dis1']<200)&
	(data1.index%9==0),data1['wo_new'],np.where((data1['dis1']>= 200)&(data1.index%9!=0) ,data1['wo_id'], data1['wo_new'])))
    data1['wo_new']=data1['wo_new'].shift(1)

程序处理200万条数据只需要耗时5分钟,效率非常快,以后在处理csv或excel文件,可以多使用np.where,在此分享给大家,欢迎交流!

猜你喜欢

转载自blog.csdn.net/weilangao/article/details/88927642