如何将 Pandas Dataframe 转换为 NumPy 数组

Asad Riaz 2021年7月18日 2020年2月27日 Pandas Pandas DataFrame

`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'>
``````

相关文章 - Pandas DataFrame

• 如何将 Pandas DataFrame 列标题获取为列表
• 如何删除 Pandas DataFrame 列
• 如何在 Pandas 中将 DataFrame 列转换为日期时间
• 如何在 Pandas DataFrame 中将浮点数转换为整数
• 如何按一列的值对 Pandas DataFrame 进行排序
• 如何用 group-by 和 sum 获得 Pandas 总和