Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating new columns by generating a multiples of 2

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading