如何将函数应用于循环中表的行

2024-04-24 23:31:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的函数,它读取两个纬度,如果它们彼此靠近,它将返回“空闲”

def is_idle(lat1, lat2):

    if lat1 - lat2 < 0.1:
        return 'idle'
    elif lat1 - lat2 > 0.1:
        return 'active'
    else:
        return 'error'

在python上,如何在循环中将其应用于循环中的行对?你知道吗


Tags: 函数returnifisdeferrorelse中将
3条回答

你是说像这样?你知道吗

def is_idle(lat1, lat2):

    if lat1 - lat2 < 0.1:
        return 'idle'
    elif lat1 - lat2 > 0.1:
        return 'active'
    else:
        return 'error'


lats = [1,2,3,4,5,6,7,8,9]

for i in range(len(lats)-1):
    lat1= lats[i]
    lat2 = lats[i+1]
    is_idle(lat1,lat2)

另一个选项是使用map、lambda和zip,而不是for循环:

lats = [1,2,3,4,5,6,7,8,9]
L = zip(lats[:-1], lats[1:]) # L = [(1,2),(2,3), ...]
map(lambda l: is_idle(l[0],l[1]), L)

或者

map(lambda l: is_idle(*l), L)

我意识到最初的问题是关于for循环,但是我建议这是一个不使用for loop的好例子。你知道吗

以下是我的解决方案:

def is_idle2(e):
    if e > 0.1:
        return 'idle'
    elif e < 0.1:
        return 'active'
    return 'error'

lats = pd.Series([5, 2, 1, 4, 5, 6]*100000)

(lats - lats.shift(1)).dropna().map(is_idle2)

时间安排:

#my solution
%timeit (lats - lats.shift(1)).dropna().map(is_idle2)
10 loops, best of 3: 185 ms per loop

#Currently accepted solution
%%timeit
for i in range(len(lats)-1):
    lat1= lats[i]
    lat2 = lats[i+1]
    is_idle(lat1,lat2)
1 loops, best of 3: 15.8 s per loop

在没有for循环的情况下这样做,对于一个大小适中的系列来说,速度要快大约100倍。你知道吗

相关问题 更多 >