Applying/Composing a function N times to a pandas column, N being different for each row

pierre_loic :

Suppose we have this simple 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

I would like to create a new column, say modified_value, that applies a function N times to the value column, N being the quantity column. Suppose that function is new_value = round(value/2, 1), the expected result would be:

   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

What would be an elegant/vectorized way to do so?

Quang Hoang :

You can write a custom repeat function, then use 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'])]

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=379226&siteId=1