+3 votes
in Programming Languages by (73.8k points)
How can I convert a pandas dataframe to a numpy array?

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

You can either values or to_numpy() to get a Numpy representation of the DataFrame.

Here is an example:

>>> import pandas as pd
>>> df = pd.DataFrame({'A': [ 1,2,3,4], 'B': [11,22,33,44], 'C': [111,222,333,444]})
>>> df
   A   B    C
0  1  11  111
1  2  22  222
2  3  33  333
3  4  44  444

>>> df.values
array([[  1,  11, 111],
       [  2,  22, 222],
       [  3,  33, 333],
       [  4,  44, 444]])

>>> df.to_numpy()
array([[  1,  11, 111],
       [  2,  22, 222],
       [  3,  33, 333],
       [  4,  44, 444]])


...