python如何把每一行数据分成3个矩阵?

How to devide each raw of data into 3 matrixes in python?

我有 1034 列的数据,我想将它的每个原始数据分成 3 个 49*7 的矩阵。它仍然是 5 列删除它们。我如何在 python 中执行此操作?

首先,我从数据中删除了最后 5 列。

rawData = pd.read_csv('../input/smartgrid/data/data.csv')#import the data

         #remove the last 5 columns
            rawData.pop('2016/9/9')
            rawData.pop('2016/9/8')
            rawData.pop('2016/9/7')
            rawData.pop('2016/9/6')
            rawData.pop('2016/9/5')            

然后,它发生了数据的预处理。之后,它被馈送到这个函数,该函数应该将每一行分成三个矩阵 week1week2week3

def CNN2D(X_train, X_test, y_train, y_test):
    print('2D - Convolutional Neural Network:')
 #Transforming every row of the train set into a 2D array
            n_array_X_train = X_train.to_numpy()
    #devided n_array_Xtrain into 3 matrixes in order to apply it in convolution layer like RGB color
           week1= [] # the first matrix
           week2= [] # the second matrix
           week3= [] # the third matrix

这里有一种方法可以满足您的要求:

import pandas as pd
import numpy as np
#rawData = pd.read_csv('../input/smartgrid/data/data.csv')#import the data
rawData = pd.DataFrame([[x * 5 + i for x in range(1034)] for i in range(2)], columns=range(1034))

numRowsPerMatrix = len(rawData.columns) // 7 // 3
numColsNeeded = 3 * 7 * numRowsPerMatrix
rawData = rawData.T.iloc[:numColsNeeded].T

for i in range(len(rawData.index)):
    n_array_X_train = rawData.iloc[i].to_numpy()
    week1= np.reshape(n_array_X_train[:49 * 7], (49, 7)) # the first matrix
    week2= np.reshape(n_array_X_train[49 * 7: 2 * 49 * 7], (49, 7)) # the second matrix
    week3= np.reshape(n_array_X_train[2 * 49 * 7:], (49, 7)) # the third matrix

rawData = rawData.T.iloc[:numColsNeeded].T 转置数组,仅对所需的行进行切片(原始 df 中的列,除了最后 5 列),然后将其转置回去。

对 week1、week2 和 week3 的赋值将 rawData 的当前行中的 1D numpy 数组的连续三分之一切片,并将每个数组重塑为 49 行乘 7 列的矩阵。