PYTHON:不断迭代行并根据行内的值更改值,直到满足条件

PYTHON: Continually iterating over row(s) and changing values based on values within the row until condition is met

我有一个数据框,其中包含多行人员配置值(上限)和分配。

我需要反复遍历每一行,直到我的分配达到我的人员配备值。我的分配从 0 开始。一旦我的分配达到我的人员配置值,就转到下一行。

这只是我正在构建的程序的第一部分,稍后我会有更多限制,这就是为什么我不只是将我的分配设置为我的人员配置值的原因。

我已经尝试了以下方法,但我收到错误消息 FutureWarning: get_value 已弃用,将在未来的版本中删除。请改用 .at[].iat[] 访问器。

for row in springdf.index:
    q = springdf.get_value(row,'Allocation')
    if q:
        p = springdf.get_value(row, 'StaffingStandardValue')
        while q < p:
            springdf.set_value(row, 'Allocation', q+1)

也尝试过:

for row in springdf.index:
        q = springdf.iloc(row,'Allocation')
        if q:
            p = springdf.iloc(row, 'StaffingStandardValue')
            if q < p:
                 springdf.set_value(row, 'Allocation', q+1)

但收到错误:__call__() takes from 1 to 2 positional arguments but 3 were given

我需要实际覆盖旧分配的值并在 "Allocating" 时更改数据帧,而不仅仅是 return 结果。该数据帧最终将输出到 excel 文件中。

感谢您的帮助!

对于索引值,我建议使用 df.loc[],您可以按名称 select 列:df['column_name']。把这些放在一起你会得到:

for row in springdf.index:
    q = springdf['Allocation'].loc[row]
    if q:
        p = springdf['StaffingStandardValue'].loc[row]
        while q < p:
            springdf['Allocation'].loc[row] = q + 1
            q = springdf['Allocation'].loc[row]

根据您的错误消息,备选方案是:

for row in springdf.index:
    q = springdf.at[row, 'Allocation']
    if q:
        p = springdf.at[row, 'StaffingStandardValue']
        while q < p:
            springdf.at[row, 'Allocation'] = q + 1
            q = springdf.at[row, 'Allocation']

我自己没有测试过,但我感觉第二个选项在性能方面更快。

编辑:我刚刚对其进行了测试,第二个选项(使用 df.at[])对于 10 行 2 列的随机数 DataFrame 快了 1000 倍以上(10.1 毫秒对 14.2 秒)。