这个问题之前肯定已经以多种形式被问过,但是,我一直无法找到一个包含多个系列输入以及 while 循环的问题。因此我的问题是:
在 while 循环之前不需要 for 循环,是否可以从此函数输出一系列:
def modify_to_100(first, second):
combined = first + second
while combined != 100:
combined += 1
return abs(combined)
我将多个 pandas 系列传递给该函数。该系列的长度始终相同。
In [132]: first = pd.Series([50, 60, 40])
In [133]: second = pd.Series([20, 10, 40])
In [134]: modify_to_100(first,second)
我得到的错误 - 这是相当具有描述性且可以理解的。但是,由于该系列的每个元素都需要不同数量的循环,因此我不知道处理这种情况的最佳方法。
Out [134]: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
作为示例,我尝试了 a.all()
,正如预期的那样,这会导致循环永远进行。永远不会出现 all() 数字加 1 并同时达到 100 的情况。
其他a.empty()、a.bool()、a.item()、a.any()
似乎不适用。我是否误解了其中一个可能允许该系列的每个元素单独进展的因素?
到目前为止,我发现的所有内容都表明 for 循环是必要的。 我想避免在这里逐行进行。
期望的输出:
100, 100, 100
任何帮助、澄清或有效的进展方式将不胜感激。
最佳答案
您正在比较一系列与标量值。组合是一个系列,而100是一个数值。
您可以将系列转换为数据帧并传递到函数中。
def modify_to_100(df):
df['new'] = df['first'] + df['second']
# df['new'] = np.where(df['new']!=100, 100, df['new'])
while True:
if all(df['new'].eq(100)):
break
df[df['new']<100] = df['new']+1
return df['new'].values
first = pd.Series([50, 60, 40])
second = pd.Series([20, 10, 40])
print(modify_to_100(pd.DataFrame({'first':first.values, 'second':second.values})))
关于python - 使用 While 循环时序列的真值不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55310328/