gpt4 book ai didi

python - 我们如何将 Python Pandas DataFrame reshape 为 C-Contiguous 内存?

转载 作者:行者123 更新时间:2023-12-03 17:39:55 32 4
gpt4 key购买 nike

我正在使用 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_train、y_train 数据帧传递给某些库时,我收到一条错误消息,指出缓冲区不再是 C 连续的。
BufferError: memoryview: underlying buffer is not C-contiguous

我的问题是:如何制作 X_train、y_train C 连续缓冲区?我尝试使用 C 和 F 选项进行整形,但没有运气。

编辑:以下是数据帧的形状、dtype 和标志:
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
)

最佳答案

我们无法直接控制 DataFrame 如何存储其值,这些值可以是 c-contiguous 的,也可以不是。但是,使用 numpy 函数 ascontiguousarray 很容易获得 C 连续数据。在底层 numpy 数组上,由 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 的文档可以在这里找到:
https://numpy.org/doc/stable/reference/generated/numpy.ascontiguousarray.html

关于python - 我们如何将 Python Pandas DataFrame reshape 为 C-Contiguous 内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38961054/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com