You can use lambda function within .apply()
and access the column values by syntax like x['A']
for column A
values, etc. For each function parameter, just put the corresponding x['A']
, x['B']
at the correct position of the function call, like cpt_p(x['A'], x['B'])
for passing value of column A
as first parameter and value of column B
as second parameter (for each row):
def cpt_p(A, B):
p = [A] * int(B) # Creates a repeating value of A of length B i.e. [A, A, A, ...]
return p
df['C'] = df.apply(lambda x: cpt_p(x['A'], x['B']), axis=1)
Another method:
Another method to apply a function to rows is by list(map())
, like below:
df['C'] = list(map(cpt_p, df['A'], df['B']))
You can put the function as the first parameter to map()
function and pass the function parameters as second parameter onwards to map()
.
The advantage of using list(map())
is that it is generally faster than using apply()
on axis=1
. Could be more than 3x times faster execution time. You can see this post
for the execution time comparison for some use cases.
Result:
print(df)
A B C
0 120.0 109 [120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, 120.0, ...]
1 108.6 147 [108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, 108.6, ...]