Convert pandas dataframe to NumPy array

前端 未结 15 2337
别那么骄傲
别那么骄傲 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:37

    It seems like df.to_records() will work for you. The exact feature you're looking for was requested and to_records pointed to as an alternative.

    I tried this out locally using your example, and that call yields something very similar to the output you were looking for:

    rec.array([(1, nan, 0.2, nan), (2, nan, nan, 0.5), (3, nan, 0.2, 0.5),
           (4, 0.1, 0.2, nan), (5, 0.1, 0.2, 0.5), (6, 0.1, nan, 0.5),
           (7, 0.1, nan, nan)],
          dtype=[(u'ID', '

    Note that this is a recarray rather than an array. You could move the result in to regular numpy array by calling its constructor as np.array(df.to_records()).

提交回复
热议问题