【问题标题】:(Python)Localizing variable(Python)本地化变量
【发布时间】:2022-01-05 15:35:46
【问题描述】:

我的目标是使用 my_function 更改数据帧 df,然后将结果分配给数据帧 df。 但是当我使用函数时,函数外部的数据帧 df 会发生变化。 如何修改函数而不影响函数之外的 df 变量?

import pandas as pd
df = pd.DataFrame({'A': [10, 20, 30]}, index=['2021-11-24', '2021-11-25', '2021-11-26'])


def my_function(df_temp):
    df_temp['A'][0] = 100  # How could I modify not to affect df varable which is outside of funtion
    return df_temp         

   something = my_function(df)
   print(df)   # df is already altered although I didn't assign

# df = my_function(df)
# print(df)

【问题讨论】:

    标签: python function pass-by-reference pass-by-value


    【解决方案1】:

    试试这些解决方案

    1. 使用 pandas.apply 函数
    import pandas as pd
    df = pd.DataFrame({'A': [10, 20, 30]}, index=['2021-11-24', '2021-11-25', '2021-11-26'])
    
    
    def my_function(row):
        row[0] = 100       
        return row
    
    
    something = df.apply(my_function)
    print(something)
    
    A
    2021-11-24  100
    2021-11-25  20
    2021-11-26  30
    
    print(df)
    
    
    A
    2021-11-24  10
    2021-11-25  20
    2021-11-26  30
    



    2.使用pandas.copy函数

    import pandas as pd
    df = pd.DataFrame({'A': [10, 20, 30]}, index=['2021-11-24', '2021-11-25', '2021-11-26'])
    
    def my_function(df):
        temp_df = df.copy()
        temp_df['A'][0] = 100
        return temp_df
    
    
    something = my_function(df)
    print(something)
    
    A
    2021-11-24  100
    2021-11-25  20
    2021-11-26  30
    
    print(df)
    
    
    A
    2021-11-24  10
    2021-11-25  20
    2021-11-26  30
    

    【讨论】:

      【解决方案2】:

      在 Python 中,参数总是通过赋值传递,因此 DataFrame 在函数内部发生了变异。优先处理引用,因为它不会影响性能。

      如果强制保留原始对象,可以手动创建副本来执行操作。

      import pandas as pd
      df = pd.DataFrame({'A': [10, 20, 30]}, index=['2021-11-24', '2021-11-25', '2021-11-26'])
      
      def my_function(df_temp):
          df_temp['A'][0] = 99
      
      dfc = df.copy()
      my_function(dfc) # alter the copy
      
      print(df) # unchanged
      print(dfc) # altered
      

      您可以在文档中阅读有关传递变量的更多信息: https://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多