重塑列表以匹配python中的特定尺寸

问题描述 投票:0回答:1

我想为特定列表指定一些表尺寸,调整形状到该尺寸,然后显示为数据框。

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

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                    

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

python pandas numpy reshape
1个回答
0
投票

[检查它,看看它是否对您有用...这里的主要工作者是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的文档-您可能会找到更多更适合您的用例的信息

© www.soinside.com 2019 - 2024. All rights reserved.