I have a data frame of multiple columns. I want to select the first column and produce 7 more by multiplying the first column in multiples of 2. Help out, please
I tried creating more columns, but the data is not transferred to the new columns.
>Solution :
Assuming such an input:
import pandas as pd
df = pd.DataFrame({'col': [1,2,3,10]})
An efficient approach would be to use numpy broadcasting:
import numpy as np
N = 7
nums = 2**np.arange(1, N+1)
out = df.join(pd.DataFrame(
df.iloc[:, 0].to_numpy()[:,None]*nums,
index=df.index, columns=nums
).rename(columns=lambda x: f'*{x}')
)
print(out)
Output:
col *2 *4 *8 *16 *32 *64 *128
0 1 2 4 8 16 32 64 128
1 2 4 8 16 32 64 128 256
2 3 6 12 24 48 96 192 384
3 10 20 40 80 160 320 640 1280