Python 从(可能的)递归函数创建新列

Python 从(可能的)递归函数创建新列,python,pandas,Python,Pandas,我有一些类似的数据: labels = ["sku", "buildfrom", "factor", "quantity"] records = [("pipe5", "pipe10", 2, 1), ("pipe10", "pipe20", 2, 4), ("pipe20", "pipe20", 1, 3)] df = pd.DataFrame.from_records(records, columns=labels) 在此数据中,pipe5是一个可用数量为1的产品,但是pipe5可以由p

我有一些类似的数据:

labels = ["sku", "buildfrom", "factor", "quantity"]
records = [("pipe5", "pipe10", 2, 1),
("pipe10", "pipe20", 2, 4),
("pipe20", "pipe20", 1, 3)]

df = pd.DataFrame.from_records(records, columns=labels)
在此数据中,pipe5是一个可用数量为1的产品,但是pipe5可以由pipe10制成,如buildfrom列所示。“因子”列中的值2表示buildfrom项可以生成2个sku项单位。 我想创建一个名为“can_make_qty”的列,并用我们可以提供的sku的可能总量填充它。 在这种情况下,“可生产数量”值应为:

  • 管道20的3(因为buildfrom==sku的值,系数为1)
  • 10用于管道10(4来自其自身库存+管道20的(2*3))
  • 21用于管道5(1来自其自身库存+管道10(2*10))
我在这里看到了递归逻辑的一些用法,但我不知道如何将其编码到函数中,以便将结果添加到“can_make_qty”中


任何帮助都将不胜感激。

好吧,我用递归解决方案做到了这一点,它适用于上述情况:

def canmake(row):
    final=[]
    final.append(row['quantity'])
    item = row['buildfrom']
    factor = row['factor']

    def recsearch(item, factor):
    # Since the buildfrom is different from item
    # I need to find the quantity of the item the can build the row['sku'] item
    # And multiply it by the factor from the row being analyzed
    # I have to search it in the *whole* DataFrame list
        qty = df[df['sku'] == item]['quantity'].values[0]

        final.append(qty*factor)
    # collect the new factor
        newfactor = df[df['sku'] == item]['factor'].values[0]
        factor *= newfactor
    # if the one searched has the same name for its sku and buildfrom then we don't
    # need to go any further, else do this:
        if (df[df['sku'] == item]['buildfrom'].values[0]) != (df[df['sku'] == item]['sku'].values[0]):

            item = df[df['sku'] == item]['buildfrom'].values[0]
            recsearch(item, factor)


    if row['buildfrom'] != row['sku']:
        recsearch(item, factor)

    return final # reduce(operator.add, final)

df['can_make_qty']=df.apply(canmake, axis=1)