如何将 Pandas Dataframe 转换为 Numpy 数组?

关注者
3
被浏览
116,328
登录后你可以
不限量看优质回答 私信答主深度交流 精彩内容一键收藏

下面我们将介绍两种方法

1.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'>

可以通过以下方法使用 Dataframe.values 方法来实现:

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

如果我们想在 NumPy 数组中包含 indexes ,则需要对 Dataframe.values 应用 reset_index()

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

2.to_records() 方法将 Dataframe 转换为 NumPy 记录数组

如果你需要 dtypes ,则 to_records() 是最好的选择。在性能方面, to_numpy() to_records() 几乎相同:

# 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)