我认为答案非常明显,但我现在还没有看到.
如何将记录数组转换回常规ndarray?
假设我有以下简单的结构化数组:
x = np.array([(1.0, 4.0,), (2.0, -1.0)], dtype=[('f0', '<f8'), ('f1', '<f8')])
Run Code Online (Sandbox Code Playgroud)
然后我想将其转换为:
array([[ 1., 4.],
[ 2., -1.]])
Run Code Online (Sandbox Code Playgroud)
我试过asarray和astype,但没有奏效.
UPDATE(求解:float32(f4)而不是float64(f8))
好的,我尝试了Robert(x.view(np.float64).reshape(x.shape + (-1,))
)的解决方案,并且使用简单的数组它可以完美地工作.但是对于我想要转换的数组,它给出了一个奇怪的结果:
data = np.array([ (0.014793682843446732, 0.006681123282760382, 0.0, 0.0, 0.0, 0.0008984912419691682, 0.0, 0.013475529849529266, 0.0, 0.0),
(0.014793682843446732, 0.006681123282760382, 0.0, 0.0, 0.0, 0.0008984912419691682, 0.0, 0.013475529849529266, 0.0, 0.0),
(0.014776384457945824, 0.006656022742390633, 0.0, 0.0, 0.0, 0.0008901208057068288, 0.0, 0.013350814580917358, 0.0, 0.0),
(0.011928378604352474, 0.002819152781739831, 0.0, 0.0, 0.0, 0.0012627150863409042, 0.0, 0.018906937912106514, 0.0, 0.0),
(0.011928378604352474, 0.002819152781739831, 0.0, 0.0, 0.0, 0.001259754877537489, …Run Code Online (Sandbox Code Playgroud) 我将从使用CSV加载的结构化数组转换np.genfromtxt为a np.array以使数据适合Scikit-Learn估算器时遇到困难.问题是在某些时候会发生从结构化数组到常规数组的转换,从而导致a ValueError: can't cast from structure to non-structure.很长一段时间,我一直在用它.view来执行转换,但这导致NumPy发布了一些弃用警告.代码如下:
import numpy as np
from sklearn.ensemble import GradientBoostingClassifier
data = np.genfromtxt(path, dtype=float, delimiter=',', names=True)
target = "occupancy"
features = [
"temperature", "relative_humidity", "light", "C02", "humidity"
]
# Doesn't work directly
X = data[features]
y = data[target].astype(int)
clf = GradientBoostingClassifier(random_state=42)
clf.fit(X, y)
Run Code Online (Sandbox Code Playgroud)
提出的例外是: ValueError: Can't cast from structure to non-structure, except if the structure only has a single field.
我的第二次尝试是使用如下视图:
# View is raising deprecation warnings …Run Code Online (Sandbox Code Playgroud)