熊猫矢量化而不是循环

时间:2017-10-19 15:34:58

标签: python pandas dataframe python-os

我有一个路径数据框。任务是使用datetime.fromtimestamp(os.path.getmtime('PATH_HERE'))之类的内容将文件夹的最后修改时间记入单独的列

import pandas as pd
import numpy as np
import os


df1 = pd.DataFrame({'Path' : ['C:\\Path1' ,'C:\\Path2', 'C:\\Path3']})

#for a MVCE use the below commented out code. WARNING!!! This WILL Create directories on your machine.
#for path in df1['Path']:
#    os.mkdir(r'PUT_YOUR_PATH_HERE\\' + os.path.basename(path))

我可以使用下面的任务完成任务,但如果我有很多文件夹,那么这是一个缓慢的循环:

for each_path in df1['Path']:
    df1.loc[df1['Path'] == each_path, 'Last Modification Time'] = datetime.fromtimestamp(os.path.getmtime(each_path))

我将如何引导此过程以提高速度? os.path.getmtime无法接受该系列。我正在寻找类似的东西:

df1['Last Modification Time'] = datetime.fromtimestamp(os.path.getmtime(df1['Path']))

2 个答案:

答案 0 :(得分:0)

您可以使用groupby transform(这样您每个群组只能拨打一次昂贵的电话):

g = df1.groupby("Path")["Path"]
s = pd.to_datetime(g.transform(lambda x: os.path.getmtime(x.name)))
df1["Last Modification Time"] = s  # putting this on two lines so it looks nicer...

答案 1 :(得分:0)

我将提出3种方法,假设使用100条路径。我认为方法3是完全可取的。

# Data initialisation:
paths100 = ['a_whatever_path_here'] * 100
df = pd.DataFrame(columns=['paths', 'time'])
df['paths'] = paths100


def fun1():
    # Naive for loop. High readability, slow.
    for path in df['paths']:
        mask = df['paths'] == path
        df.loc[mask, 'time'] = datetime.fromtimestamp(os.path.getmtime(path))


def fun2():
    # Naive for loop optimised. Medium readability, medium speed.
    for i, path in enumerate(df['paths']):
        df.loc[i, 'time'] = datetime.fromtimestamp(os.path.getmtime(path))


def fun3():
    # List comprehension. High readability, high speed.
    df['time'] = [datetime.fromtimestamp(os.path.getmtime(path)) for path in df['paths']]


% timeit fun1()
>>> 164 ms ± 2.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

% timeit fun2()
>>> 11.6 ms ± 67.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

% timeit fun3()
>>> 13.1 ns ± 0.0327 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)