python for循环优化_在python中优化循环

通常,除非绝对必要,否则不应循环遍历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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值