我想定义一个函数,如果设置了另一个变量,则该函数将在数据帧的一部分上运行,否则将在整个数据帧上运行。例如:
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()
关于python - 为 ":"切片定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60266161/