如何使用pandas从两列创建数组

12

假设我有一个类似于这样的DataFrame:

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并将它们转换为这个数组?
array([[0, 1],
       [2, 3],
       [4, 5]])
2个回答

26
您可以通过to_numpy方法访问底层的numpy数组:
df[['col1', 'col2']].to_numpy()
Out: 
array([[0, 1],
       [2, 3],
       [4, 5]])

.values 属性在早期版本(v0.24之前)也可以实现相同的功能。


1
您也可以使用以下代码实现相同的输出。
import numpy as np
np.array(df[['col1','col2']])
Out[60]: 
array([[0, 1],
       [2, 3],
       [4, 5]])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接