Sae*_*eed 2 python function python-3.x pandas
请考虑接受两个参数的此函数:series
和categorical_values
.它的目标是获得a series
,使其成为分类,然后打印原始系列的每个元素以及分类的相应元素.但是,如果categorical_values
已经将该函数作为输入传递给函数,则跳过分类阶段,该函数只打印传递的对series
和categorical_values
.
def my_function(series, categorical_values = None):
if categorical_values: #meant to mean "if this argument is passed, just use it"
categorical_values = categorical_values
else: #meant to mean "if this argument is not passed, create it"
categorical_values= pd.qcut(series, q = 5)
for i,j in zip(series, categorical_values):
print(i, j)
Run Code Online (Sandbox Code Playgroud)
但是,传递categorical_values
以下内容:
my_function(series, pd.qcut(series, q = 5))
Run Code Online (Sandbox Code Playgroud)
导致:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Run Code Online (Sandbox Code Playgroud)
产生此错误的代码行是第一行: if categorical_values:
检查函数参数是否已通过或未通过的正确方法是什么?
由于默认值为None,因此您应该检查它是不是.
if categorical_values is not None:
...
Run Code Online (Sandbox Code Playgroud)
但是,如果块无论如何都是无操作的; 逆转它会更好:
if categorical_values is None:
categorical_values = pd.qcut(series, q = 5)
Run Code Online (Sandbox Code Playgroud)
并且你根本不需要其他块.