我想通过根据其他列值(两个或三个以上的列)为一个新列赋值来处理一个大数据集。我有下面的Python代码。你知道吗
我的数据集包含1700万条数据记录。运行脚本需要40多个小时。我是Python新手,对大数据的经验很少。你知道吗
有人能帮我加快脚本运行速度吗?你知道吗
以下是数据集的示例:
PId hZ tId tPurp ps oZ dZ oT dT
0 1 50 1040 32 762 748 10.5 12.5
0 1 50 1040 16 748 81 12.5 12.5
0 1 50 1040 2048 81 1 12.5 12.5
0 1 50 1040 1040 1 762 9.5 9.5
1 1 10 320 320 1 35 17.5 17.5
1 1 10 320 2048 35 1 19.5 19.5
2 1 50 1152 1152 297 102 11.5 12
2 1 50 1152 2048 102 1 12 12
2 1 50 1152 32 1 297 11.5 11.5
3 1 1 2 64 737 184 14 18
3 1 1 2 128 184 713 14 14
3 1 1 2 2048 184 1 18 18
3 1 1 2 2 1 737 9 9
4 1 1 2 2 1 856 9 9
4 1 1 2 2048 296 1 18 18
4 1 1 2 16 856 296 17 18
8 1 50 1056 16 97 7 15 15.5
8 1 50 1056 32 7 816 15.5 1
8 1 50 1056 2048 816 1 1 1
8 1 50 1056 1056 1 97 12 12
下面是Python代码
import pandas as pd
import numpy as np
df_test = pd.read_csv("C:/users/test.csv")
df_test.sort_values(by=['PId','tId','oT','dT'],inplace=True)
ls2t = df_test.groupby(['PId','tId']).nth(-2)
ls2t.reset_index(level=(0,1),inplace=True)
ls2tps=ls2t[['PId','tId','ps']]
ls2tps=ls2tps.rename(columns = {'ps':'ls2ps'})
df_lst = pd.merge(df_test,
ls2tps,
on=['PId','tId'],
how='left')
for index,row in df_lst.iterrows():
if df_lst.loc[index,'oZ']==df_lst.loc[index,'hZ'] and df_lst.loc[index,'ps']==2:
df_lst.loc[index,'d'] = 'A'
elif df_lst.loc[index,'oZ']==df_lst.loc[index,'hZ'] and df_lst.loc[index,'ps']!=2:
df_lst.loc[index,'d']='B'
elif df_lst.loc[index,'ps']==2048 and (df_lst.loc[index,'ls2ps']==2 or df_lst.loc[index,'ls2ps']==514):
df_lst.loc[index,'d']='A'
elif df_lst.loc[index,'ps']==2048 and (df_lst.loc[index,'ls2ps']!=2 and df_lst.loc[index,'ls2ps']!=514):
df_lst.loc[index,'d']='B'
else:
df_lst.loc[index,'d']='C'
od_aggpurp = df_lst.groupby(['oZ','dZ','d']).size().reset_index(name='counts')
od_aggpurp.to_csv('C:/users/test_result.csv')
你应该尝试以下方法来代替这个循环:
在这里,您仅从df\u lst(using.loc)中选择具有请求的参数的行,但仅修改d列。你知道吗
注意,在数据帧和之间的pandas中,或是|,不是是~。你知道吗
如果您愿意,这应该表现得更好:
相关问题 更多 >
编程相关推荐