如何填充嵌套列表



我有一个嵌套列表,其中包含1002个时间步长,在每个时间步长中,我观察到11个特性。我读过与填充相关的文档,但我真的不知道如何在每个列表的末尾添加零元素。例如,我发现列表长度最高的是主列表中的第24个项目,现在我想在此基础上填充所有其他元素,除非第24个元素已经成形。例如:

a = [[1,2,3,4,5,6,76,7],[2,2,3,4,2,5,5,5,,7,8,9,33,677,8,8,9,9],[2,3,46,7,8,9,],[3,3,3,5],[2,2],[1,1],[2,2]]
a[1] = padding(a[1],len(a[2]) with zeros at the end of the list)

我做了以下工作:

import numpy as np
def pad_or_truncate(some_list, target_len):
return some_list[:target_len] + [0]*(target_len - len(some_list))

for i in range(len(Length)):
pad_or_truncate(Length[i],len(Length[24]))

print(len(Length[i]))

for i in range(len(Length)):
df_train_array = np.pad(Length[i],len(Length[24]),mode='constant') 

我得到了这个错误:Unable to coerce to Series, length must be 11: given 375

解决方案1

# set the max number of 0
max_len = max([len(x) for x in a])
# add zeros to the lists
temp = [x+ [0]*max_len for x in a]
#Limit the output to the wished length
[x[0:max_len] for x in temp]

使用pandas的解决方案2

import pandas as pd
df = pd.DataFrame(a)
df.fillna(0).astype(int).values.tolist()

输出

[[1, 2, 3, 4, 5, 6, 76, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[2, 2, 3, 4, 2, 5, 5, 5, 7, 8, 9, 33, 677, 8, 8, 9, 9],
[2, 3, 46, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[3, 3, 3, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
...]

下面的代码片段应该用适当数量的0填充各个列表(由具有最大元素的列表的大小驱动(

def main():
data = [
[1,2,3,4,5,6,76,7],
[2,2,3,4,2,5,5,5,7,8,9,33,677,8,8,9,9],
[2,3,46,7,8,9,],
[3,3,3,5],
[2,2],
[1,1],
[2,2]
]
# find the list with the maximum elements
max_length = max(map(len, data))
for element in data:
for _ in range(len(element), max_length):
element.append(0)

if __name__ == '__main__':
main()

您可以使用这个简单的行,它使用np.pad

list(map(lambda x: np.pad(x, (max(map(len, a)) - len(x), 0)).tolist(), a))
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 76, 7],
[2, 2, 3, 4, 2, 5, 5, 5, 7, 8, 9, 33, 677, 8, 8, 9, 9],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 46, 7, 8, 9],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 5],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2]]

如果你想在结尾处填充,请使用此选项:

list(map(lambda x: np.pad(x, (0, max(map(len, a)) - len(x))).tolist(), a))

最新更新