我们如何将Python数据帧重塑为C-连续内存?

我们如何将Python数据帧重塑为C-连续内存?,python,python-3.x,pandas,numpy,scikit-learn,Python,Python 3.x,Pandas,Numpy,Scikit Learn,我正在用Pandas在内存中加载一个二维数据集,并执行4个简单的机器学习预处理任务,如添加/删除列、重新索引、训练/测试拆分 #Read file MLMe = pd.read_table("data/dtCTG.txt", ",") #Label target column to "class" MLMe.rename(columns={'NSP' : 'class'}, inplace=True) #Create train/test indices MLMe_class = MLMe['

我正在用Pandas在内存中加载一个二维数据集,并执行4个简单的机器学习预处理任务,如添加/删除列、重新索引、训练/测试拆分

#Read file
MLMe = pd.read_table("data/dtCTG.txt", ",")
#Label target column to "class"
MLMe.rename(columns={'NSP' : 'class'}, inplace=True)

#Create train/test indices
MLMe_class = MLMe['class'].values
training_indices, validation_indices = training_indices, testing_indices = train_test_split(
MLMe.index, stratify = MLMe_class, train_size=0.75, test_size=0.25)

#Create train/test data sets
X_train = MLMe.drop('class',axis=1).loc[training_indices].values
y_train = MLMe.loc[training_indices,'class'].values

X_test = MLMe.drop('class',axis=1).loc[validation_indices].values
y_test = MLMe.loc[validation_indices, 'class'].values

#Final datasets to be used for training
X_train, y_train, X_test, y_test
现在,当我将X_列、y_列数据帧传递给某些库时,我得到一条错误消息,即缓冲区不再是C连续的

BufferError: memoryview: underlying buffer is not C-contiguous
我的问题是:我如何制作X\U列车,y\U列车C-连续缓冲器?我试着用C和F选项重塑,但没有成功

编辑:以下是数据帧的形状、数据类型和标志:

X_train.shape, y_train.shape, X_test.shape, y_test.shape
((1104, 9), (1104,), (369, 9), (369,))
X_train.dtype, y_train.dtype, X_test.dtype, y_test.dtype
(dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'))
X_train.flags, y_train.flags, X_test.flags, y_test.flags
(  C_CONTIGUOUS : False
   F_CONTIGUOUS : True
   OWNDATA : False
   WRITEABLE : True
   ALIGNED : True
   UPDATEIFCOPY : False,   

   C_CONTIGUOUS : True
   F_CONTIGUOUS : True
   OWNDATA : True
   WRITEABLE : True
   ALIGNED : True
   UPDATEIFCOPY : False,   

   C_CONTIGUOUS : False
   F_CONTIGUOUS : True
   OWNDATA : False
   WRITEABLE : True
   ALIGNED : True
   UPDATEIFCOPY : False,   

   C_CONTIGUOUS : True
   F_CONTIGUOUS : True
   OWNDATA : True
   WRITEABLE : True
   ALIGNED : True
   UPDATEIFCOPY : False
)

我们无法直接控制数据帧如何存储其值,这些值可以是c连续的,也可以不是。但是,通过在基础numpy数组上使用numpy函数
ASCONTIGOUUSARRAY
很容易获得C-连续数据,该函数由数组的
value
属性返回。您可以自己测试它:

X_train.flags.c_contiguous  # Checks if the array is C-contiguous
#>>> False
X_train = np.ascontiguousarray(X_train) # Converts the array to C-contiguous
X_train.flags.c_contiguous
#>>> True
numpy.ascontiguousarray
的文档可在以下位置找到:

检查并-您可能会在那里找到一些有用的信息…向我们展示相关数组的数据类型、形状和标志。您是否尝试过
X\u train=np.ascontiguousarray(X\u train)
?我为数据集添加了数据类型、形状和标志信息。两个C_不连续:我想解决办法是使它们C_连续,但不确定如何连续。@Happy001哇,你的解决办法成功了!谢谢