如何从 pandas 中的两列创建数组 [英] How to create an array from two columns in pandas

查看:31
本文介绍了如何从 pandas 中的两列创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个与此类似的DataFrame:

suppose I have a DataFrame similar to this:

d = {'col1': [0, 2, 4], 'col2': [1, 3, 5], 'col3': [2, 4, 8]}
df = pd.DataFrame(d)

   col1  col2  col3
0     0     1     2
1     2     3     4
2     4     5     8

如何选择col1和col2并将它们转换为该数组?

How can I select col1 and col2 and turn them into this array?

array([[0, 1],
       [2, 3],
       [4, 5]])

推荐答案

您可以通过

You can access the underlying numpy array via the to_numpy method:

df[['col1', 'col2']].to_numpy()
Out: 
array([[0, 1],
       [2, 3],
       [4, 5]])


如果使用的是较低版本(v0.24之前的版本),

.values属性将执行相同的操作.


.values attribute will do the same if you are on an earlier version (before v0.24).

这篇关于如何从 pandas 中的两列创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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