将函数应用/组合 N 次到 Pandas 列,每行 N 不同

pie*_*oic 5 python pandas

假设我们有这个简单的 pandas.DataFrame:

import pandas as pd

df = pd.DataFrame(
  columns=['quantity', 'value'],
  data=[[1, 12.5], [3, 18.0]]
)

>>> print(df)
   quantity  value
0         1   12.5
1         3   18.0
Run Code Online (Sandbox Code Playgroud)

我想创建一个新列,例如modified_value,将函数应用于该value列N 次,N 是该quantity列。假设该函数为new_value = round(value/2, 1),则预期结果为:

   quantity  value  modified_value
0         1   12.5            6.2   # applied 1 time
1         3   9.0             1.1   # applied 3 times, 9.0 -> 4.5 -> 2.2 -> 1.1
Run Code Online (Sandbox Code Playgroud)

这样做的优雅/矢量化方式是什么?

Qua*_*ang 2

您可以编写自定义repeat函数,然后使用 apply:

def repeat(func, x, n):
    ret = x
    for i in range(int(n)):
        ret = func(ret)

    return ret

def my_func(val): return round(val/2, 1)

df['new_col'] = df.apply(lambda x: repeat(my_func, x['value'], x['quantity']), 
                         axis=1)

# or without apply
# df['new_col'] = [repeat(my_func, v, n) for v,n in zip(df['value'], df['quantity'])]
Run Code Online (Sandbox Code Playgroud)