Python While循环用于迭代两个值之间的所有组合

Python While循环用于迭代两个值之间的所有组合,python,while-loop,Python,While Loop,我想创建一个循环,将两个变量的所有迭代加载到单独列中的数据帧中。我希望变量“a”以0.1的增量保持0和1之间的值,变量“b”也是如此。换句话说,完成时应该有100次迭代,从0和0开始,以1和1结束 我尝试了以下代码 data = [['Decile 1', 10], ['Decile_2', 15], ['Decile_3', 14]] staging_table = pd.DataFrame(data, columns = ['Decile', 'Volume']) profile_table

我想创建一个循环,将两个变量的所有迭代加载到单独列中的数据帧中。我希望变量“a”以0.1的增量保持0和1之间的值,变量“b”也是如此。换句话说,完成时应该有100次迭代,从0和0开始,以1和1结束

我尝试了以下代码

data = [['Decile 1', 10], ['Decile_2', 15], ['Decile_3', 14]]
staging_table = pd.DataFrame(data, columns = ['Decile', 'Volume'])
profile_table = pd.DataFrame(columns = ['Decile', 'Volume'])

a = 0
b = 0

finished = False

while not finished:
    if b != 1:
        if a != 1:
            a = a + 0.1
            staging_table['CAM1_Modifier'] = a
            staging_table['CAM2_Modifier'] = b
            profile_table = profile_table.append(staging_table)
        else:
            b = b + 0.1
    else:
        finished = True  

profile_table

您可以使用itertools.product获取所有组合:

import itertools
import pandas as pd

x = [i / 10 for i in range(11)]
df = pd.DataFrame(
    list(itertools.product(x, x)),
    columns=["a", "b"]
)

#        a    b
# 0    0.0  0.0
# 1    0.0  0.1
# 2    0.0  0.2
# ...  ...  ...
# 118  1.0  0.8
# 119  1.0  0.9
# 120  1.0  1.0
# 
# [121 rows x 2 columns]

您可以使用itertools.product获取所有组合:

import itertools
import pandas as pd

x = [i / 10 for i in range(11)]
df = pd.DataFrame(
    list(itertools.product(x, x)),
    columns=["a", "b"]
)

#        a    b
# 0    0.0  0.0
# 1    0.0  0.1
# 2    0.0  0.2
# ...  ...  ...
# 118  1.0  0.8
# 119  1.0  0.9
# 120  1.0  1.0
# 
# [121 rows x 2 columns]
他是你的朋友

from itertools import product

for a, b in product(map(lambda x: x / 10, range(10)),
                    map(lambda x: x / 10, range(10))):
  ...
range(10)
为我们提供了从
0
10
的整数(遗憾的是,
range
在浮动时失败)。然后我们将这些值除以
10
,得到从
0
1
的范围。然后,我们把这个可数的笛卡尔积和它自身一起,得到每一个组合。

是你的朋友

from itertools import product

for a, b in product(map(lambda x: x / 10, range(10)),
                    map(lambda x: x / 10, range(10))):
  ...

range(10)
为我们提供了从
0
10
的整数(遗憾的是,
range
在浮动时失败)。然后我们将这些值除以
10
,得到从
0
1
的范围。然后我们取iterable的笛卡尔积,得到每个组合。

你永远不会重置a。你应该在else子句中这样做。将“b!=1”与“finished”条件分开也没有意义——直接将其放入while语句中。是的,我想就是这样,我还必须使a<1而不是a!=1,但现在运行良好。谢谢,你从来没有重置过。你应该在else子句中这样做。将“b!=1”与“finished”条件分开也没有意义——直接将其放入while语句中。是的,我想就是这样,我还必须使a<1而不是a!=1,但现在运行良好。谢谢