Home > Enterprise >  assign a shorter column to a longer column, given a sliding winow
assign a shorter column to a longer column, given a sliding winow

Time:08-02

I have this dataframe df1 of 8 rows:

ID

A
B
C
D
E
F
G
H

And I have this array arr of size 4 [-1, 0, 1, 2], and an m = 2, so I want to assign the values of this array jumping m times to df1, so I can have eventually:

ID      N

A      -1
B      -1 
C       0
D       0
E       1
F       1
G       2
H       2

How to do that in Python?

CodePudding user response:

df1=pd.DataFrame({'ID':['A','B', 'C', 'D', 'E', 'F', 'G', 'H']})
arr=[-1,0,1,2]
m=2

If arr should be repeated again and again:

df1['N']=(arr*m)[:len(df1)]

Result:

ID N
0 A -1
1 B 0
2 C 1
3 D 2
4 E -1

If each element should be repeated:

df1['N']=[arr[i] for i in range(len(arr)) for j in range(m)][:len(df1)]

Result:

ID N
0 A -1
1 B -1
2 C 0
3 D 0
4 E 1

CodePudding user response:

~~ Without numpy

arr = [-1, 0, 1, 2]
m = 2
df1["N"] = sum([[x]*m for x in arr], [])

~~ With Numpy

import numpy as np
arr = [-1, 0, 1, 2]
m = 2
df1["N"] = np.repeat(arr, m)

Output:

    ID  N
0   A   -1
1   B   -1
2   C   0
3   D   0
4   E   1
5   F   1
6   G   2
7   H   2
  • Related