【问题标题】:Python - how to build a function that has the option "inplace"Python - 如何构建具有“就地”选项的函数
【发布时间】:2021-04-02 15:41:28
【问题描述】:

我应该如何从头开始构建一个具有inplace 选项的函数,就像pd.rename(inplace=True) 中的函数一样?

想象这样的事情:

def my_func(df=, inplace=):
    some_code_that_process_df
    if inplace == False:
        return df
    else:
        # what should I code in here?

【问题讨论】:

  • 允许对可以具有默认值的 arg 进行就地处理似乎很危险......
  • inplace 暗示函数(虽然通常它是一个方法)改变对象。所以改变对象而不是创建一个新对象。

标签: python pandas function dataframe


【解决方案1】:

您可以通过复制或对原始数据框进行操作来做到这一点。您可以通过像这样比较对象 id 来保证原始数据帧在整个处理过程中都完成了:

def my_func(df, inplace=False):

    df_id = id(df)

    if not inplace:
        df = df.copy(deep=True)

    # example processing:
    df.rename(columns={col:col+"_new" for col in df.columns}, inplace=True)

    if inplace and (id(df) != df_id):
        raise ValueError("original dataframe has been lost")
    
    # usually only copies return the df, but I'll leave it for an example
    return df

这是一个示例,我们显示 id 相同/已更改。请注意,如果我们执行了df = df.rename(...),该函数将失败,因为后续处理不会在原始数据帧上执行。

df = pd.DataFrame(dict(x=[1,2,3]))

df2 = my_func(df, inplace=True)
df3 = my_func(df, inplace=False)

print(df is df2) # True
print(df is df3) # False

【讨论】:

    猜你喜欢
    • 2021-07-21
    • 2021-04-01
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    相关资源
    最近更新 更多