【问题标题】:make 3d numpy array using for loop in python在 python 中使用 for 循环制作 3d numpy 数组
【发布时间】:2023-02-06 14:58:35
【问题描述】:

我有二维的训练数据。 (4 个特征的 200 个结果)

我证明了 100 个不同的应用程序,重复 10 次产生了 1000 个 csv 文件。

我想堆叠每个 csv 结果以进行机器学习。 但我不知道怎么办。

我的每个 csv 文件如下所示。

test1.csv 到 numpy 数组数据

[[0 'crc32_pclmul' 445 0]
 [0 'crc32_pclmul' 270 4096]
 [0 'crc32_pclmul' 234 8192]
 ...
 [249 'intel_pmt' 272 4096]
 [249 'intel_pmt' 224 8192]
 [249 'intel_pmt' 268 12288]]

我试过下面的python代码。

path = os.getcwd()
csv_files = glob.glob(os.path.join(path, "*.csv"))
cnt=0
for f in csv_files:
    cnt +=1
    seperator = '_'
    app = os.path.basename(f).split(seperator, 1)[0]

    if cnt==1:
        a = np.array(preprocess(f))
        b = np.array(app)
    else:
        a = np.vstack((a, np.array(preprocess(f))))
        b = np.append(b,app)
print(a)
print(b)

预处理函数返回每个 csv 文件的 df.to_numpy 结果。

我的期望如下。一个 (1000, 200, 4)

[[[0 'crc32_pclmul' 445 0]
 [0 'crc32_pclmul' 270 4096]
 [0 'crc32_pclmul' 234 8192]
 ...
 [249 'intel_pmt' 272 4096]
 [249 'intel_pmt' 224 8192]
 [249 'intel_pmt' 268 12288]],
[[0 'crc32_pclmul' 445 0]
 [0 'crc32_pclmul' 270 4096]
 [0 'crc32_pclmul' 234 8192]
 ...
 [249 'intel_pmt' 272 4096]
 [249 'intel_pmt' 224 8192]
 [249 'intel_pmt' 268 12288]],
...
[[0 'crc32_pclmul' 445 0]
 [0 'crc32_pclmul' 270 4096]
 [0 'crc32_pclmul' 234 8192]
 ...
 [249 'intel_pmt' 272 4096]
 [249 'intel_pmt' 224 8192]
 [249 'intel_pmt' 268 12288]]]

但是,我明白了。一个(200000,4)

[[0 'crc32_pclmul' 445 0]
 [0 'crc32_pclmul' 270 4096]
 [0 'crc32_pclmul' 234 8192]
 ...
 [249 'intel_pmt' 272 4096]
 [249 'intel_pmt' 224 8192]
 [249 'intel_pmt' 268 12288]]

我想使用 a[0] 访问每个 csv 结果到 a[1000] 每个子数组看起来像 (200,4) 我该如何解决这个问题?我迷路了

【问题讨论】:

    标签: python arrays numpy 3d 2d


    【解决方案1】:

    制作一个新列表并在阅读后将每个列表附加到该新列表。 (在循环外创建新列表)

    【讨论】:

      【解决方案2】:

      您必须从vstack 更改为stack

      a = np.stack((a, np.array(preprocess(f))), axis=0) 
      

      vstack 只能沿行堆叠,但 stack 函数可以沿新轴堆叠。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-29
        • 1970-01-01
        • 2021-01-04
        • 1970-01-01
        • 2022-01-25
        • 1970-01-01
        • 2011-07-04
        • 1970-01-01
        相关资源
        最近更新 更多