小编dim*_*myG的帖子

基于同一列的先前值对列值进行矢量化计算?

我有一个包含2列的pandas数据框,如下所示:

df = pd.DataFrame(data={'A': [10, 2, 3, 4, 5, 6], 'B': [0, 1, 2, 3, 4, 5]})

>>> df 
     A  B
 0  10  0
 1   2  1
 2   3  2
 3   4  3
 4   5  4
 5   6  5
Run Code Online (Sandbox Code Playgroud)

我想以下列方式创建一个新列C:C [i] = C [i-1] -A [i] + B [i]

在这个问题中,答案建议使用这样的循环:

df['C'] = df['A']

for i in range(1, len(df)):
    df['C'][i] = df['C'][i-1] - df['A'][i] + df['B'][i] 

>>> df
    A  B   C
0  10  0  10
1   2  1   9 …
Run Code Online (Sandbox Code Playgroud)

python vectorization pandas difference

5
推荐指数
1
解决办法
143
查看次数

Python,调用进程池而不阻塞事件循环

如果我运行以下代码:

import asyncio
import time
import concurrent.futures

def cpu_bound(mul):
    for i in range(mul*10**8):
        i+=1
    print('result = ', i)
    return i

async def say_after(delay, what):
    print('sleeping async...')
    await asyncio.sleep(delay)
    print(what)

# The run_in_pool function must not block the event loop
async def run_in_pool():
    with concurrent.futures.ProcessPoolExecutor() as executor:
        result = executor.map(cpu_bound, [1, 1, 1])

async def main():
    task1 = asyncio.create_task(say_after(0.1, 'hello'))
    task2 = asyncio.create_task(run_in_pool())
    task3 = asyncio.create_task(say_after(0.1, 'world'))

    print(f"started at {time.strftime('%X')}")
    await task1
    await task2
    await task3
    print(f"finished at {time.strftime('%X')}")

if __name__ …
Run Code Online (Sandbox Code Playgroud)

python event-loop coroutine python-asyncio python-multiprocessing

3
推荐指数
1
解决办法
3359
查看次数