Python :如果没有传递参数,则函数作用于 initial/default 值
Python : Function which works on initial/default values if no parameters are passed
我定义了一个函数,它计算我的数据框中的列 Test 1
在两个时间限制之间的平均值。
数据帧是-:-
df = pd.DataFrame({'Time':[0.0, 0.25, 0.5, 0.68, 0.94, 1.25, 1.65, 1.88,
2.05, 2.98, 3.45, 3.99, 4.06],'Test 1':[5, 9, 4, 6, 4, 1, 6, 8, 2, 9, 3, 9, 4]})
而函数是-:-
def custom_mean(x,y):
return df.loc[df['Time'].between(x,y), 'Test 1'].mean()
函数custom_mean(x,y)
计算两个时间限制x
和y
之间的平均值。我如何定义一个函数或编写一段代码,它在传递参数时做完全相同的事情(计算两个限制之间的平均值),如果没有参数则计算从第一个值到最后一个值的整列的平均值通过(例如,与我的数据框中从 0.00 到 4.06 的时间限制对应的值的平均值)?
您可以将最小值和最大值设置为默认值:
def custom_mean(x=df.Time.min(), y=df.Time.max()):
return df.loc[df['Time'].between(x,y), 'Test 1'].mean()
custom_mean()
会给出 5.384615384615385
.
您可以将函数参数的初始值设置为 None
,如下所示:
def custom_mean(x=None, y=None):
# if either of x or y is None, return the mean of whole column
if x is None or y is None:
return df['Test 1'].mean()
# otherwise, filter and get mean
return df.loc[df['Time'].between(x,y), 'Test 1'].mean()
>>> custom_mean()
5.384615384615385
>>> custom_mean(x=0.0, y=2.05)
5.0
>>> custom_mean(x=0.0, y=0.6)
6.0
我定义了一个函数,它计算我的数据框中的列 Test 1
在两个时间限制之间的平均值。
数据帧是-:-
df = pd.DataFrame({'Time':[0.0, 0.25, 0.5, 0.68, 0.94, 1.25, 1.65, 1.88,
2.05, 2.98, 3.45, 3.99, 4.06],'Test 1':[5, 9, 4, 6, 4, 1, 6, 8, 2, 9, 3, 9, 4]})
而函数是-:-
def custom_mean(x,y):
return df.loc[df['Time'].between(x,y), 'Test 1'].mean()
函数custom_mean(x,y)
计算两个时间限制x
和y
之间的平均值。我如何定义一个函数或编写一段代码,它在传递参数时做完全相同的事情(计算两个限制之间的平均值),如果没有参数则计算从第一个值到最后一个值的整列的平均值通过(例如,与我的数据框中从 0.00 到 4.06 的时间限制对应的值的平均值)?
您可以将最小值和最大值设置为默认值:
def custom_mean(x=df.Time.min(), y=df.Time.max()):
return df.loc[df['Time'].between(x,y), 'Test 1'].mean()
custom_mean()
会给出 5.384615384615385
.
您可以将函数参数的初始值设置为 None
,如下所示:
def custom_mean(x=None, y=None):
# if either of x or y is None, return the mean of whole column
if x is None or y is None:
return df['Test 1'].mean()
# otherwise, filter and get mean
return df.loc[df['Time'].between(x,y), 'Test 1'].mean()
>>> custom_mean()
5.384615384615385
>>> custom_mean(x=0.0, y=2.05)
5.0
>>> custom_mean(x=0.0, y=0.6)
6.0