Question #6306   Submitted by Answiki on 06/22/2022 at 07:43:48 PM UTC

In Python, how to create NumPy array from a Pandas Dataframe?

Answer   Submitted by Answiki on 12/31/2020 at 06:37:49 PM UTC

In Python, the best way to convert a Pandas Dataframe to a NumPy array is to use the method pandas.DataFrame.to_numpy() :

>>> import pandas as pd
>>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]])
>>> df.to_numpy()
array([[1, 2, 3],
       [4, 5, 6]])

By default, a view is returned: any modifications made will affect the original.

>>> array = df.to_numpy()
>>> array[0,0] = -1
>>> df
   	0	1	2 
0 	-1	2	3
1	4	5	6

To get a copy, use the copy=True option:

df.to_numpy(copy=True)

5 events in history
Question by Answiki 06/22/2022 at 07:43:48 PM
In Python, how to create NumPy array from a Pandas Dataframe?
Answer by Answiki on 12/31/2020 at 06:37:49 PM

In Python, the best way to convert a Pandas Dataframe to a NumPy array is to use the method pandas.DataFrame.to_numpy() :

>>> import pandas as pd
>>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]])
>>> df.to_numpy()
array([[1, 2, 3],
       [4, 5, 6]])

By default, a view is returned: any modifications made will affect the original.

>>> array = df.to_numpy()
>>> array[0,0] = -1
>>> df
   	0	1	2 
0 	-1	2	3
1	4	5	6

To get a copy, use the copy=True option:

df.to_numpy(copy=True)

Answer by Answiki on 12/31/2020 at 06:18:37 PM

In Python, the best way to convert a Pandas Dataframe to a NumPy array is to use the method pandas.DataFrame.to_numpy() :

>>> import pandas as pd
>>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]])
>>> df.to_numpy()
array([[1, 2, 3],
       [4, 5, 6]])

By default, a view is returned: any modifications made will affect the original.

>>> array = df.to_numpy()
>>> array[0,0] = -1
>>> df
   	0	1	2 
0 	-1	2	3
1	4	5	6

To get a copy, use the copy=True option:

to_numpy(copy=True)

Answer by Answiki on 12/31/2020 at 06:14:06 PM

In Python, the best way to convert a Pandas Dataframe to a NumPy array is to use the method pandas.DataFrame.to_numpy() :

>>> import pandas as pd
>>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]])
>>> df.to_numpy()
array([[1, 2, 3],
       [4, 5, 6]])

By default, a view is returned: any modifications made will affect the original.

>>> array = df.to_numpy()
>>> array[0,0] = -1
>>> df
   	0	1	2 
0 	-1	2	3
1	4	5	6

To get a copy, use the copy=True option:

to_numpy(copy=True)



Question by Answiki 12/31/2020 at 06:04:49 PM
In Python, how to convert a Pandas Dataframe to NumPy array?
# ID Query URL Count

Icons proudly provided by Friconix.