# 如何將 Pandas Dataframe 轉換為 NumPy 陣列

## `to_numpy` 方法將 `DataFrame` 轉換為 `NumPy` 陣列

`pandas.Dataframe` 是具有行和列的二維表格資料結構。可以使用 `to_numpy` 方法將該資料結構轉換為 `NumPy` 陣列：

``````# python 3.x
import pandas as pd
import numpy as np

df = pd.DataFrame(data=np.random.randint(0, 10, (6, 4)), columns=["a", "b", "c", "d"])
nmp = df.to_numpy()
print(nmp)
print(type(nmp))
``````

``````[[5 5 1 3]
[1 6 6 0]
[9 1 2 0]
[9 3 5 3]
[7 9 4 9]
[8 1 8 9]]
<class 'numpy.ndarray'>
``````

``````# python 3.x
import pandas as pd
import numpy as np

df = pd.DataFrame(data=np.random.randint(0, 10, (6, 4)), columns=["a", "b", "c", "d"])
nmp = df.values
print(nmp)
print(type(nmp))
``````

``````[[8 8 5 0]
[1 7 7 5]
[0 2 4 2]
[6 8 0 7]
[6 4 5 1]
[1 8 4 7]]
<class 'numpy.ndarray'>
``````

``````# python 3.x
import pandas as pd
import numpy as np

df = pd.DataFrame(data=np.random.randint(0, 10, (6, 4)), columns=["a", "b", "c", "d"])
nmp = df.reset_index().values
print(nmp)
print(type(nmp))
``````

``````[[0 1 0 3 7]
[1 8 2 5 1]
[2 2 2 7 3]
[3 3 4 3 7]
[4 5 4 4 3]
[5 2 9 7 6]]
<class 'numpy.ndarray'>
``````

## `to_records()` 方法將 `DataFrame` 轉換為 `NumPy` 記錄陣列

``````# python 3.x
import pandas as pd
import numpy as np

df = pd.DataFrame(data=np.random.randint(0, 10, (6, 4)), columns=["a", "b", "c", "d"])
nmp = df.to_records()
print(nmp)
print(type(nmp))
``````

``````[(0, 0, 4, 6, 1)
(1, 3, 1, 7, 1)
(2, 9, 1, 6, 4)
(3, 1, 4, 6, 9)
(4, 9, 1, 3, 9)
(5, 2, 5, 7, 9)]
<class 'numpy.recarray'>
``````