Dataframe指定列转化为矩阵matrix、数组list

废话不多说,直接上代码

import numpy as np
import pandas as pd

#创建数据框data
data=pd.DataFrame(np.arange(16).reshape(4,4),index=list('ABCD'),columns=list('EFGH'))
'''
    E   F   G   H
A   0   1   2   3
B   4   5   6   7
C   8   9  10  11
D  12  13  14  15
'''

#将所有数据输出为矩阵
data.as_matrix()
'''
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
'''

#将指定列输出为矩阵
data[['E','F']].as_matrix()
'''
array([[ 0,  1],
       [ 4,  5],
       [ 8,  9],
       [12, 13]])
'''
#将制定列输出为数组
data['E'].tolist()
'''
[0, 4, 8, 12]
'''

猜你喜欢

转载自blog.csdn.net/W_weiying/article/details/80923850
今日推荐