【问题标题】:Why do my values not change after running my function? [duplicate]为什么我的值在运行我的函数后没有改变? [复制]
【发布时间】:2021-05-10 17:12:17
【问题描述】:

我正在尝试从列中删除异常值。假设我有:

rand_df = pd.DataFrame({"A": [1,2,3], 'B': [4,5,6]})

如果我这样做:

rand_df = rand_df[rand_df['A'] > 2]

我得到了一个我想要的新 df。但是,如果我尝试:

def some_fxn(df, col):
    df = df[df[col] > 2]

some_fxn(rand_df, 'A')

我的 df 没有改变。我需要做什么才能使这个功能正常运行?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您期望通过引用行为。 Python 既没有按引用传递,也没有按值传递。它只有bindings to names

    以下代码显示了当对象的 ID 发生变化时

    import pandas as pd
    rand_df = pd.DataFrame({"A": [1,2,3], 'B': [4,5,6]})
    rand_df = rand_df[rand_df['A'] > 2]
    print(rand_df)
    
    
    def some_fxn(df, col):
        print(id(df))
        df = df[df[col] > 2]
        print(id(df))
        
    rand_df = pd.DataFrame({"A": [1,2,3], 'B': [4,5,6]})
    some_fxn(rand_df, 'A')
    print(rand_df)
    

    所以你别无选择,只能返回新值。

    【讨论】:

      【解决方案2】:

      您需要在函数末尾使用return。没有显式 return 语句的函数返回 None。

      def some_fxn(df, col):
          return df[df[col] > 2]
      
      some_fxn(rand_df, 'A')
      
      Out[412]: 
         A  B
      2  3  6
      

      【讨论】:

        【解决方案3】:

        尽量不要在函数调用中赋值,而是返回并赋值:

        def some_fxn(df, col):
            return df[df[col] > 2]
        
        df = some_fxn(rand_df, 'A') # assign to df for updating or any other variable for copy
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-25
          • 2014-07-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-20
          相关资源
          最近更新 更多