Python:从DataFrame中的两列创建结构化numpy结构化数组 [英] Python: Create structured numpy structured array from two columns in a DataFrame

查看:451
本文介绍了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')])

有什么区别?

很少. recarrayndarray(常规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结构化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆