通常,除非绝对必要,否则不应循环遍历DataFrames.通常,使用已经优化的内置Pandas函数或使用矢量化方法,可以获得更好的性能.
在这种情况下,可以使用loc和Boolean indexing进行分配:
# 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