如何从DataFrame中的两列创建结构化数组? 我试过了:
How do you create a structured array from two columns in a DataFrame? I tried this:
df = pd.DataFrame(data=[[1,2],[10,20]], columns=['a','b']) df a b 0 1 2 1 10 20 x = np.array([([val for val in list(df['a'])], [val for val in list(df['b'])])])但这给了我这个:
array([[[ 1, 10], [ 2, 20]]])但是我想要这个:
[(1,2),(10,20)]谢谢!
推荐答案有两种方法.与常规的NumPy阵列相比,您可能会在性能和功能上遭受损失.
There are a couple of methods. You may experience a loss in performance and functionality relative to regular NumPy arrays.
您可以使用 pd.DataFrame.to_records 使用index=False.从技术上讲,这是一个记录数组,但对于许多目的就足够了.
You can use pd.DataFrame.to_records with index=False. Technically, this is a record array, but for many purposes this will be sufficient.
res1 = df.to_records(index=False) print(res1) rec.array([(1, 2), (10, 20)], dtype=[('a', '<i8'), ('b', '<i8')])结构化数组
手动地,您可以通过逐行转换为tuple,然后为dtype参数指定元组列表来构造结构化数组.
structured array
Manually, you can construct a structured array via conversion to tuple by row, then specifying a list of tuples for the dtype parameter.
s = df.dtypes res2 = np.array([tuple(x) for x in df.values], dtype=list(zip(s.index, s))) print(res2) array([(1, 2), (10, 20)], dtype=[('a', '<i8'), ('b', '<i8')])有什么区别?
很少. recarray是ndarray(常规NumPy数组类型)的子类.另一方面,第二个示例中的结构化数组的类型为ndarray.
Very little. recarray is a subclass of ndarray, the regular NumPy array type. On the other hand, the structured array in the second example is of type ndarray.
type(res1) # numpy.recarray isinstance(res1, np.ndarray) # True type(res2) # numpy.ndarray主要区别是记录数组便于属性查找,而结构化数组将产生AttributeError:
The main difference is record arrays facilitate attribute lookup, while structured arrays will yield AttributeError:
print(res1.a) array([ 1, 10], dtype=int64) print(res2.a) AttributeError: 'numpy.ndarray' object has no attribute 'a'相关: NumPy记录数组"或结构化数组"或"recarray"
更多推荐
Python:从DataFrame中的两列创建结构化numpy结构化数组
发布评论