Convert pandas dataframe to NumPy array

前端 未结 15 2361
别那么骄傲
别那么骄傲 2020-11-21 23:57

I am interested in knowing how to convert a pandas dataframe into a NumPy array.

dataframe:

import numpy as np
import pandas as pd

index = [1, 2, 3,         


        
15条回答
  •  伪装坚强ぢ
    2020-11-22 00:31

    A Simpler Way for Example DataFrame:

    df
    
             gbm       nnet        reg
    0  12.097439  12.047437  12.100953
    1  12.109811  12.070209  12.095288
    2  11.720734  11.622139  11.740523
    3  11.824557  11.926414  11.926527
    4  11.800868  11.727730  11.729737
    5  12.490984  12.502440  12.530894
    

    USE:

    np.array(df.to_records().view(type=np.matrix))
    

    GET:

    array([[(0, 12.097439  , 12.047437, 12.10095324),
            (1, 12.10981081, 12.070209, 12.09528824),
            (2, 11.72073428, 11.622139, 11.74052253),
            (3, 11.82455653, 11.926414, 11.92652727),
            (4, 11.80086775, 11.72773 , 11.72973699),
            (5, 12.49098389, 12.50244 , 12.53089367)]],
    dtype=(numpy.record, [('index', '

提交回复
热议问题