python - 使用 While 循环时序列的真值不明确

标签 python pandas dataframe

这个问题之前肯定已经以多种形式被问过,但是,我一直无法找到一个包含多个系列输入以及 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/

相关文章:

python - 在Python中将2个文本文件合并为一个具有2列的文本文件

python - 包含字符串和 float 的 Pandas Dataframe 列

python - 以毫秒为单位分配时间以获得平滑曲线

python - 使用 np.where 在一系列多个值上创建另一个包含 1 和 0 的列

python - 转换 Pandas 数据框,其中列条目是列标题

python - 使用 Python 正则表达式分割字符串

python - Numpy power 不允许负值

python - 无法访问同一类中的另一个函数 (Python)

python-3.x - pandas 数据框列转换

python - 将复合值转换为 pandas 数据框中的列