如何创建两列的大熊猫
问题描述:
假设我有一个类似的数据帧的数组:如何创建两列的大熊猫
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]])
答
您可以通过.values
属性访问底层numpy的数组:
df[['col1', 'col2']].values
Out:
array([[0, 1],
[2, 3],
[4, 5]])
答
也可以实现与下面的代码相同的输出。
import numpy as np
np.array(df[['col1','col2']])
Out[60]:
array([[0, 1],
[2, 3],
[4, 5]])