Python:从DataFrame中的两列创建结构化numpy结构化数组

编程入门 行业动态 更新时间:2024-10-28 16:19:17
本文介绍了Python:从DataFrame中的两列创建结构化numpy结构化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何从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结构化数组

本文发布于:2023-10-28 08:56:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536157.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:结构化   数组   Python   DataFrame   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!