baxx
baxx

Reputation: 4725

Reshape list to match particular dimension in python

I would like to specify some table dimension for a particular list, reshape to that dimension and then display as a dataframe.

For example, for _list above, if I wanted to display that as a 5x5 table it would look as:

import random
import string

random.seed(1)
N = 21
_list = ["".join(random.sample(string.ascii_letters, 3)) for _ in range(N)]

dimension = 5 * 5
buffer = ["" for _ in range(dimension - len(_list))]
_list = _list + buffer

pd.DataFrame(np.array(_list).reshape(5, 5))

which outputs

     0    1    2    3    4
0  iKZ  Weq  hFW  CEP  yYn
1  gFb  yBM  WXa  SCr  UZo
2  Lgu  bPI  ayR  nBU  bHo
3  WCF  Jow  oRW  Dsb  AJP
4  glO                    

I feel as though this approach is quite clunky though, and that there is a more appropriate approach.

Upvotes: 1

Views: 938

Answers (1)

sammywemmy
sammywemmy

Reputation: 28709

Check this and see if it works for you ... the main worker here is resize, and setting refcheck to False, since we are not sharing the memory with another array

#convert list to an array
num = np.array(_list)

#resize and set refcheck to False
# it is a new object and memory for this array has not been shared with another 
num.resize((5,5), refcheck=False)

#print num
num

array([['iKZ', 'Weq', 'hFW', 'CEP', 'yYn'],
       ['gFb', 'yBM', 'WXa', 'SCr', 'UZo'],
       ['Lgu', 'bPI', 'ayR', 'nBU', 'bHo'],
       ['WCF', 'Jow', 'oRW', 'Dsb', 'AJP'],
       ['glO', '', '', '', '']], dtype='<U3')

Have a look at the docs for resize - u might find more info better suited for ur use case

Upvotes: 3

Related Questions