我有一个具有行进距离的数据框(df),并且已根据某些条件分配了标签。
distance=[0,0.0001,0.20,1.23,4.0]
df = pd.DataFrame(distance,columns=["distance"])
df['label']=0
for i in range(0, len(df['distance'])):
if (df['distance'].values[i])<=0.10:
df['label'][i]=1
elif (df['distance'].values[i])<=0.50:
df['label'][i]=2
elif (df['distance'].values[i])>0.50:
df['label'][i]=3
一切正常。但是,我有超过100万条具有距离的记录,并且此for循环花费的时间比预期的长。我们可以优化此代码以减少执行时间吗?
通常,除非绝对必要,否则不应循环遍历DataFrames。通常,使用已经优化的内置Pandas函数或使用矢量化方法,可以获得更好的性能。
在这种情况下,可以使用loc
和布尔索引进行分配:
# Initialize as 1 (eliminate need to check the first condition).
df['label'] = 1
# Case 1: Between 0.1 and 0.5
df.loc[(df['distance'] > 0.1) & (df['distance'] <= 0.5), 'label'] = 2
# Case 2: Greater than 0.5
df.loc[df['distance'] > 0.5, 'label'] = 3
另一种选择是使用pd.cut
。这是一种对问题中的示例问题更加专业的方法。布尔索引是一种更通用的方法。
# Get the low and high bins.
low, high = df['distance'].min()-1, df['distance'].max()+1
# Perform the cut. Add one since the labels start at zero by default.
df['label'] = pd.cut(df['distance'], bins=[low, 0.1, 0.5, high], labels=False) + 1
您也可以labels=[1,2,3]
在上面的代码中使用,而不要在结果中加1。但这将给出df['labels']
分类dtype而不是整数dtype。根据您的用例,这可能重要也可能不重要。
两种方法的结果输出:
distance label
0 0.0000 1
1 0.0001 1
2 0.2000 2
3 1.2300 3
4 4.0000 3
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句