首页 文章

我如何传递:作为python中的函数参数?

提问于
浏览
2

我正在使用python3和pandas,我想传递 : 作为函数参数来声明传递给 df.loc 的切片中的所有行 .

例如,假设我有一个填充na值的函数,如下所示:

def fill_na_w_value(df, rows, columns, fill):

    for col in columns:
        df.loc[rows, columns].fillna(
            fill,
            inplace=True
        )

有时候我可能不想将它应用到某些行但是要将它应用到 all rows ,在pandas中这可以通过 df.loc[:, col] 访问

如果我从一个它想要的函数调用它

fill_na_w_value(df, :, ['col1'], 0)

但由于 : ,上面会给我一个语法错误;如何将其作为函数参数传递?

1 回答

  • 2

    使用 slice(None) 表示 : . 注意,您可以使用pipe通过函数传递数据帧,loc接受行和索引过滤的列表:

    df = pd.DataFrame({'col1': [1, 2, np.nan, 4, 5, np.nan, 7, 8, np.nan]})
    
    def fill_na_w_value(df, row_slicer, columns, value):
        df.loc[row_slicer, columns] = df.loc[row_slicer, columns].fillna(value)
        return df
    
    df1 = df.pipe(fill_na_w_value, slice(None), ['col1'], 0)
    
    print(df1)
    
       col1
    0   1.0
    1   2.0
    2   0.0
    3   4.0
    4   5.0
    5   0.0
    6   7.0
    7   8.0
    8   0.0
    

    这是使用 list 而不是slice对象的示例:

    df2 = df.pipe(fill_na_w_value, [2, 5], ['col1'], 0)
    
    print(df2)
    
       col1
    0   1.0
    1   2.0
    2   0.0
    3   4.0
    4   5.0
    5   0.0
    6   7.0
    7   8.0
    8   NaN
    

相关问题