1

i have the following dataset

        x     y

0      0.5    1.5
1      2.5    3.5
2      1.5    2.5
3      4.5    5.5

i would like to generate a column with the range of numbers from x to y with a step of 0.5....

      x        y          range
0    0.5      1.5      [0.5, 1.0, 1.5]
1    2.5      3.5      [2.5, 3.0, 3.5]
2    1.5      2.5      [1.5, 2.0, 2.5]
3    4.5      5.5      [4.5, 5.0, 5.5]

how do i go about this?

2 Answers2

0

It is possible, but if performance is important, it is not good idea:

df['range'] = [np.arange(s, e + .5, .5) for s, e in zip(df['x'], df['y'])]
print (df)
     x    y            range
0  0.5  1.5  [0.5, 1.0, 1.5]
1  2.5  3.5  [2.5, 3.0, 3.5]
2  1.5  2.5  [1.5, 2.0, 2.5]
3  4.5  5.5  [4.5, 5.0, 5.5]
jezrael
  • 629,482
  • 62
  • 918
  • 895
0

Using apply to make it fancy:

import numpy as np

df['range'] = df.apply(lambda x: np.arange(x[0],x[1]+1e-9,0.5), axis=1)
print(df)

     x    y            range
0  0.5  1.5  [0.5, 1.0, 1.5]
1  2.5  3.5  [2.5, 3.0, 3.5]
2  1.5  2.5  [1.5, 2.0, 2.5]
3  4.5  5.5  [4.5, 5.0, 5.5]

Note: the axis=1 applies the function row-wise

ibarrond
  • 3,987
  • 1
  • 14
  • 33