Python循环未正确附加到列表

2024-09-29 21:59:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个小数组。。你知道吗

  lot_id  S1  S2  S3  S4
1       A   1   2   3   4
2       A   5   6   7   8
3       A   9  10  11  12
4       B  13  14  15  16
5       B  17  18  19  20
6       B  21  22  23  24
7       C  25  26  27  28
8       C  29  30  31  32
9       C  33  34  35  36
10      D  37  38  39  40
11      D  41  42  43  44
12      D  45  46  47  48
13      E  49  50  51  52
14      E  53  54  55  56
15      E  57  58  59  60
16      F  61  62  63  64
17      F  65  66  67  68
18      F  69  70  71  72
19      G  73  74  75  76
20      G  77  78  79  80
21      G  81  82  83  84

我按lot\u id循环,选择数据子集,然后将其添加到一个新列表中——然而,这种行为很奇怪。当我在最后查看列表时,它似乎只存储了最后一个lot id元素的第i次。。?你知道吗

列表应该包含以下内容。。。你知道吗

A
(10, 4)
[[ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]
 [ 9. 10. 11. 12.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]]
B
(10, 4)
[[13. 14. 15. 16.]
 [17. 18. 19. 20.]
 [21. 22. 23. 24.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]]
C
(10, 4)
[[25. 26. 27. 28.]
 [29. 30. 31. 32.]
 [33. 34. 35. 36.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]]

等等。。。。。。 但它实际上包含了。。。你知道吗

[array([[73., 74., 75., 76.],
       [77., 78., 79., 80.],
       [81., 82., 83., 84.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]]), array([[73., 74., 75., 76.],
       [77., 78., 79., 80.],
       [81., 82., 83., 84.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]]), array([[73., 74., 75., 76.],
       [77., 78., 79., 80.],
       [81., 82., 83., 84.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],

我是,在循环中也是零填充。。。你知道吗

这是密码。。你知道吗

lotids = dummy['lot_id'].unique()
temp = np.zeros(shape=(10,4)) #template to pad to
lsttest2 = [] #define empty list

lots = len(lotids)
for i in range(lots):
    lot = lotids[i]

    lotsub = dummy[dummy.lot_id==lot]
    lotsub = lotsub.to_numpy()

    lotsub = np.delete(lotsub, 0, 1) #remove the lot_id col
    temp[:lotsub.shape[0],:lotsub.shape[1]] = lotsub #add it to the all zero array to pad out
    print(temp.shape)
    print(temp)
    lsttest2.append(temp)
    print("this is the end of loop---", i, " the list now has ", len(lsttest2), " elements")
    print(lsttest2)

我不明白为什么最后一个循环元素会被复制到列表中的每一个第I个条目。。?你知道吗


Tags: thetoid元素列表nparraytemp

热门问题