Currently, I am using the apply method on my dataframe in order to create a computed column which contains lists of variable sizes (depending on the value in the length column).
Is there a way to create a column with variable-sized lists more efficiently with pandas?
import pandas as pd
import numpy as np
df = pd.DataFrame({'a': [1, 2, 3, 4, 5], 'b': [
6, 7, 8, 9, 0], 'length': [3, 5, 7, 9, 3]})
df['computed'] = df.apply(
lambda x: np.array([x['a'], x['b']] + [x['b'] + i for i in range(1, x['length'] - 1)]), axis=1)
Desired output (works with code above, but slow):
a b length computed
0 1 6 3 [1, 6, 7]
1 2 7 5 [2, 7, 8, 9, 10]
2 3 8 7 [3, 8, 9, 10, 11, 12, 13]
3 4 9 9 [4, 9, 10, 11, 12, 13, 14, 15, 16]
4 5 0 3 [5, 0, 1]