osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

using zip for transpose


Robin Becker wrote:

> In conversion of pandas dataframe to reportlab table I suggested using
> this expression
> 
> [list(x) for x in map(list,zip(*[df[i].values for i in df]))]
> 
> which effectively transposes the dataframe. However, it's not clear that
> this works for a large number of rows. Is the argument *A for A a large
> list just copied into the zip *args; I suppose calling
> zip(A[0],A[1],......A[len(A)-1]) cannot be how this is done.

Isn't df.values a numpy array? Then try the more direct and likely more 
efficient

df.values.tolist()

or, if you ever want to transpose

df.values.T.tolist()

The first seems to achieve what your sample code does. (In addition it also 
converts the numpy type to the corresponding python builtin, i. e. 
numpy.float64 becomes float etc.)