Jason
Jason

Reputation: 467

How to add multiple rows with decreasing values into a series

I have a series of number:

5138
22498
42955

I would like add 3 numbers (decrease 1 each) to each number above:

5135
5136
5137
5138
22495
22496
22497
22498
42952
42953
42954
42955

How to do that? Thanks.

Upvotes: 2

Views: 88

Answers (2)

Bruce Salcedo
Bruce Salcedo

Reputation: 192

I did this on python:

numbers = [5138, 22498, 42955]
for number in numbers:
    for i in reversed(range(number, number-4, -1)):
        print(i)

Hope this helps :)

Upvotes: 2

jezrael
jezrael

Reputation: 863166

Use list comprehension with flatten new values created by range:

s = pd.Series([5138,22498,42955])

N = 3
a = pd.Series([y for x in s for y in range(x-N, x+1)])
print (a)
0      5135
1      5136
2      5137
3      5138
4     22495
5     22496
6     22497
7     22498
8     42952
9     42953
10    42954
11    42955
dtype: int64

Or is possible create ranges and flatten by Series.explode, last Series.reset_index is used for default index:

N = 3
a = s.apply(lambda x: range(x-N, x+1)).explode().reset_index(drop=True)

Upvotes: 6

Related Questions