我想定义一个函数,如果设置了另一个变量,该函数将在数据框的一部分上运行,否则将在整个数据框上运行。例如:
def mean_loc(df, col_name, idx=None):
if idx is not None:
return df.loc[idx, col_name].mean()
else:
return df[col_name].mean()
这很好,但是我想知道是否可以做这样的事情:
def mean_loc_2(df, col_name, idx=None):
if idx is None:
idx = :
return df.loc[idx, col_name].mean()
这当然行不通,但我想知道是否存在旁路?如果我执行idx = df.index
,则对df.loc[df.index, col_name]
的评估要比进行df.loc[:, col_name]
的方式长得多。我尝试通过执行slice
从内置函数中使用idx = slice(len(df))
,但没有成功(它也更长,并且不适用于DateTime索引)。
有人知道该怎么做吗?
:
不是值;它是Python语法的一部分。您需要的是slice
语法表示的:
对象。
if idx is None:
idx = slice(None) # sadly, slice() does not work
由于slice
对象是不可变的,因此可以安全地使用一个作为默认参数值。
def mean_loc_2(df, col_name, idx=slice(None)):
return df.loc[idx, col_name].mean()