python - 通过添加 nan 使所有子列表长度相同

标签 python

如何通过在每个子列表上添加 np.nan 来使我的所有子列表具有相同的长度(最长子列表的长度)?

import random
[list(range(0,random.randint(1,5))) for x in range(n)]

所以如果输出是:

[[0, 1], [0], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3]]

它应该是这样的:

[[nan,nan,nan,0, 1], [nan,nan,nan,nan,0], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [nan,0, 1, 2, 3]]

最佳答案

首先,使用max() 找到最长子列表的长度。然后,对于每个子列表,使用切片赋值将该列表的内容替换为正确数量的 NaN,后跟原始列表。

import random, math

n = 5
lists = [list(range(0,random.randint(1,5))) for x in range(n)]

# get the maximum length
maxlen = len(max(lists, key=len))

# pad left of each sublist with NaN to make it as long as the longest
for sublist in lists:
    sublist[:] = [math.nan] * (maxlen - len(sublist)) + sublist

关于python - 通过添加 nan 使所有子列表长度相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53400016/

相关文章:

python - 将请求response.content放入队列后multiprocessing.Process不会终止

python - 文件名有空格的 Pyspark 错误处理

python - pyOpenGL 三角形没有被绘制

python - 如何在旧数组成员之间插入空白或无

python - Stackdriver 调试 appengine 错误 : python module not found

Python Pandas : Group by one column and see the content of all columns?

Python 随机 随机

Python Excel 负数和正数出现的次数(计数/频率)

python - pyqt:消息框在几秒钟后自动关闭

python - 如何在 django 模板中执行查询过滤