Home > Enterprise >  Iteratively pop and append to generate new lists using pandas
Iteratively pop and append to generate new lists using pandas

Time:11-11

I have a list of elements mylist = [1, 2, 3, 4, 5, 6, 7, 8] and would like to iteratively:

  1. copy the list
  2. pop the first element of the copied list
  3. and append it to the end of the copied list
  4. repeat this for the next row, etc.

Desired output:

index   A   B   C   D   E   F   G   H
0       1   2   3   4   5   6   7   8
1       2   3   4   5   6   7   8   1
2       3   4   5   6   7   8   1   2
3       4   5   6   7   8   1   2   3
4       5   6   7   8   1   2   3   4
5       6   7   8   1   2   3   4   5
6       7   8   1   2   3   4   5   6
7       8   1   2   3   4   5   6   7

I suspect a for loop is needed but am having trouble iteratively generating rows based on the prior row.

CodePudding user response:

I think slicing (Understanding slicing) is what you are looking for:

next_iteration =  my_list[1:]   [my_list[0]]

and the full loop:

output = []
for i in range(len(my_list)):
    output.append(my_list[i:]   my_list[:i])

CodePudding user response:

Use this numpy solution with rolls create by np.arange:

mylist = [1, 2, 3, 4, 5, 6, 7, 8]

a = np.array(mylist)
rolls = np.arange(0, -8, -1)
print (rolls)
[ 0 -1 -2 -3 -4 -5 -6 -7]

df = pd.DataFrame(a[(np.arange(len(a))[:,None]-rolls) % len(a)], 
                  columns=list('ABCDEFGH'))
print (df)
   A  B  C  D  E  F  G  H
0  1  2  3  4  5  6  7  8
1  2  3  4  5  6  7  8  1
2  3  4  5  6  7  8  1  2
3  4  5  6  7  8  1  2  3
4  5  6  7  8  1  2  3  4
5  6  7  8  1  2  3  4  5
6  7  8  1  2  3  4  5  6
7  8  1  2  3  4  5  6  7

If need loop solution (slow) is possible use numpy.roll:

mylist = [1, 2, 3, 4, 5, 6, 7, 8]

rolls = np.arange(0, -8, -1)

df = pd.DataFrame([np.roll(mylist, i) for i in rolls], 
                  columns=list('ABCDEFGH'))
print (df)
   A  B  C  D  E  F  G  H
0  1  2  3  4  5  6  7  8
1  2  3  4  5  6  7  8  1
2  3  4  5  6  7  8  1  2
3  4  5  6  7  8  1  2  3
4  5  6  7  8  1  2  3  4
5  6  7  8  1  2  3  4  5
6  7  8  1  2  3  4  5  6
7  8  1  2  3  4  5  6  7

CodePudding user response:

try this:

mylist = [1, 2, 3, 4, 5, 6, 7, 8]
ar = np.roll(np.array(mylist), 1)
data = [ar := np.roll(ar, -1) for _ in range(ar.size)]
df = pd.DataFrame(data, columns=[*'ABCDEFGH'])
print(df)
>>>
   A  B  C  D  E  F  G  H
0  1  2  3  4  5  6  7  8
1  2  3  4  5  6  7  8  1
2  3  4  5  6  7  8  1  2
3  4  5  6  7  8  1  2  3
4  5  6  7  8  1  2  3  4
5  6  7  8  1  2  3  4  5
6  7  8  1  2  3  4  5  6
7  8  1  2  3  4  5  6  7
  • Related