I l@ve RuBoard Previous Section Next Section

1.17 Transposing Two-Dimensional Arrays

Credit: Steve Holden

1.17.1 Problem

You need to transpose a list of lists, turning rows into columns and vice versa.

1.17.2 Solution

You must start with a list whose items are lists all of the same length:

arr = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]

A list comprehension offers a simple, handy way to transpose it:

print [[r[col] for r in arr] for col in range(len(arr[0]))]
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]

1.17.3 Discussion

This recipe shows a concise way (although not necessarily the fastest way) to turn rows into columns. List comprehensions are known for being concise.

Sometimes data just comes at you the wrong way. For instance, if you use Microsoft's ADO database interface, due to array element ordering differences between Python and Microsoft's preferred implementation language (Visual Basic), the GetRows method actually appears to return database columns in Python, despite its name. This recipe's solution to this common problem was chosen to demonstrate nested list comprehensions.

Notice that the inner comprehension varies what is selected from (the row), while the outer comprehension varies the selector (the column). This process achieves the required transposition.

If you're transposing large arrays of numbers, consider Numeric Python and other third-party packages. Numeric Python defines transposition and other axis-swinging routines that will make your head spin.

1.17.4 See Also

The Reference Manual section on list displays (the other name for list comprehensions); Numeric Python (http://www.pfdubois.com/numpy/).

    I l@ve RuBoard Previous Section Next Section