2017-04-01 153 views
0

假設我有一個類似的數據幀的數組:如何創建兩列的大熊貓

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]]) 

回答

3

您可以通過.values屬性訪問底層numpy的數組:

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

也可以實現與下面的代碼相同的輸出。

import numpy as np 
np.array(df[['col1','col2']]) 
Out[60]: 
array([[0, 1], 
     [2, 3], 
     [4, 5]])