应用函数需要很长时间才能 运行

apply function takes a long time to run

我正在处理大约 32.000.000 行的数据集:

RangeIndex: 32084542 entries, 0 to 32084541

df.head()


        time                        device      kpi                                 value
0   2020-10-22 00:04:03+00:00       1-xxxx  chassis.routing-engine.0.cpu-idle   100
1   2020-10-22 00:04:06+00:00       2-yyyy  chassis.routing-engine.0.cpu-idle   97
2   2020-10-22 00:04:07+00:00       3-zzzz  chassis.routing-engine.0.cpu-idle   100
3   2020-10-22 00:04:10+00:00       4-dddd  chassis.routing-engine.0.cpu-idle   93
4   2020-10-22 00:04:10+00:00       5-rrrr  chassis.routing-engine.0.cpu-idle   99

我的目标是创建一个名为 role 的附加列,填充正则表达式

这是我的方法

def router_role(row):
    if row["device"].startswith("1"):
        row["role"] = '1'
    if row["device"].startswith("2"):
        row["role"] = '2'
    if row["device"].startswith("3"):
        row["role"] = '3'
    if row["device"].startswith("4"):
        row["role"] = '4'
    return row

然后,

df = df.apply(router_role,axis=1)

但是这会花费很多时间...对其他可能的方法有什么想法吗?

谢谢

申请很慢而且从来都不是很好。尝试这样的事情:

df['role'] = df['device'].str[0]

使用 apply 是出了名的慢,因为它没有利用多线程(例如,参见 pandas multiprocessing apply)。相反,使用内置函数:

>>> import pandas as pd
>>> df = pd.DataFrame([["some-data", "1-xxxx"], ["more-data", "1-yyyy"], ["other-data", "2-xxxx"]])
>>> df
            0       1
0   some-data  1-xxxx
1   more-data  1-yyyy
2  other-data  2-xxxx
>>> df["Derived Column"] = df[1].str.split("-", expand=True)[0]
>>> df
            0       1 Derived Column
0   some-data  1-xxxx              1
1   more-data  1-yyyy              1
2  other-data  2-xxxx              2

在这里,我假设您可能在连字符前有多个数字(例如 42-aaaa),因此需要额外的工作来拆分列并获取拆分的第一个值。如果您只是获取第一个字符,请按照 @teepee 在他们的答案中所做的操作,只需索引字符串即可。

您可以简单地将您的代码转换为使用 np.vectorize()

看这里: