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 range of numbers as a column of dataframe

My DataFrame is:

import pandas as pd

df = pd.DataFrame(
        {
           'a': [20, 100],
           'b': [2, 3],
           'dir': ['long', 'short']
        }
 )

Expected output: Creating column x:

     a  b    dir    x
0   20  2   long    [22, 24, 26]
1  100  3  short    [97, 94, 91]

Steps:

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

x is a list with length of 3. a is starting point of x and b is step that a increases/decreases depending on dir. If df.dir == long x ascends otherwise it descends.

My Attempt based on this answer:

df['x'] = np.arange(0, 3) * df.b + df.a

Which does not produce the expected output.

>Solution :

One possible option :

N = 3

sign = {"long": +1, "short": -1}

df["x"] = [
    np.arange(a+sb, a+sb*(N+1), step=sb)# .tolist() ?
    for a,sb in zip(df["a"], df["b"].mul(df["dir"].map(sign)))
]

Output :

print(df)

     a  b    dir             x
0   20  2   long  [22, 24, 26]
1  100  3  short  [97, 94, 91]

[2 rows x 4 columns]
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