重塑列表以匹配 python 中的特定维度

Reshape list to match particular dimension in python

我想为特定列表指定一些 table 维度,reshape 到该维度,然后显示为数据框。

例如,对于上面的 _list,如果我想将其显示为 5x5 table 它看起来像:

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))

输出

     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                    

虽然我觉得这种方法很笨拙,但还有更合适的方法。

检查一下,看看它是否适合你...这里的主要工作人员是 resize,并将 refcheck 设置为 False,因为我们不与另一个数组共享内存

#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')

查看 resize 的文档 - 您可能会找到更适合您的用例的更多信息