【问题标题】:apply function takes a long time to run应用函数需要很长时间才能运行
【发布时间】:2021-03-03 03:50:08
【问题描述】:

我正在处理大约 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

我的目标是创建一个名为角色的附加列,其中填充了一个正则表达式

这是我的方法

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)

但是这需要很多时间......关于其他可能的方法的任何想法?

谢谢

【问题讨论】:

    标签: python pandas dataframe machine-learning data-science


    【解决方案1】:

    Apply 很慢,而且从来都不是很好。试试这样的:

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

    【讨论】:

    • 非常感谢,简单快捷
    • 就像有人指出的那样,如果您处理的数字比router_role 函数中显示的数字多,最好使用这个:df['role'] = df['device'].str.extract('^(\d+)')
    【解决方案2】:

    使用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 在他们的回答中所做的,只需索引字符串即可。

    【讨论】:

      【解决方案3】:

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

      请看这里: Performance of Pandas apply vs np.vectorize to create new column from existing columns

      【讨论】:

        猜你喜欢
        • 2013-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-20
        • 2021-06-15
        相关资源
        最近更新 更多