Doubt to transpose part of a table with Python

Asked

Viewed 340 times

2

I need help to build a Python script that transposes part of a csv as in the example below:

[[0A,0B,0C,0D,0E,0F]
[01,02,03,04,05,06]
[07,08,09,10,11,12]
[13,14,15,16,17,18]
[19,20,21,22,23,24]]

therein:

[[0A,0B,0C]
[01,02,03]
[01,02,04]
[01,02,05]
[01,02,06]
[07,08,09]
[07,08,10]
[07,08,11]
.
.
.
[19,20,24]]

Has anyone ever done this kind of transposition of a csv/xls via python ?

  • Never forget to post what you tried to do to solve the problem, even to give a basis for who will answer.

1 answer

1


Using map and chain:

from itertools import chain

data = [[10,11,12,13,14,15],
[1,2,3,4,5,6],
[7,8,9,10,11,12],
[13,14,15,16,17,18],
[19,20,21,22,23,24]]

result = chain(*map(lambda line: [line[:2] + [line[i]] for i in range(2, 6)], data))
print(list(result))

[[10, 11, 12], [10, 11, 13], [10, 11, 14], [10, 11, 15], [1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 2, 6], [7, 8, 9], [7, 8, 10], [7, 8, 11], [7, 8, 12], [13, 14, 15], [13, 14, 16], [13, 14, 17], [13, 14, 18], [19, 20, 21], [19, 20, 22], [19, 20, 23], [19, 20, 24]]

In place of chain, you can use sum if you don’t mind:

result = sum(map(lambda line: [line[:2] + [line[i]] for i in range(2, 6)], data), [])
  • 1

    Thank you very much ! worked out here !

  • 1

    Sharing the other code that worked: result = [M[0][:3]] + list(chain(*[x[:2] + [y] for y in x[2:]] for x in M[1:]]))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.