将基于条件的列添加到df的有效方法

2024-10-01 00:15:03 发布

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

我有一个带有两列的大型df:

Label                  Part_id
"Replace Cable"
"Ethernet Cable"       abc123
"Adjust Cable"
"Lubricate screw"

我希望添加一个列“solution type”,当Part_id不为空或标签上有“replace”/“[p]”字样时,该列将为“Part”,否则将采取行动

预期输出如下所示:

Label                  Part_id       Solution Type
"Replace Cable"                      Part
"Ethernet Cable"       abc123        Part
"Adjust Cable"                       Action
"Lubricate screw"                    Action

我想出了以下代码:

part_hints = r'(\[p\])|replace'

df['Solution Type'] = df.apply(lambda x: "Part" if not (pd.isnull(x.part_id)) or x.astype(str).str.contains(part_hints).any()
                                                else "Action", axis=1)

问题是它真的很慢。。。对于0.5M行的df,这可能需要两分钟的运行时间

如果你能想出办法让这更快,我将不胜感激

谢谢


Tags: iddfactionlabelreplacesolutionpartcable
2条回答

尝试使用np.where()

import numpy as np

df["Solution Type"]=np.where(
        (df['Label'].str.contains(part_hints,case=False,regex=True)) | (df['Part_id'].notna()),
        "Part",
        "Action")

您可以这样尝试:

df.loc[df.Label.str.contains("replace", case=False) | df.Part_id.notnull(), 'Solution Type'] = 'Part'

df["Solution Type"].fillna("Action", inplace = True)

相关问题 更多 >