如何将 pandas dataframe 转换为 numpy 数组
我们将来介绍 to_numpy()
方法将 pandas.dataframe
转换为 numpy
数组,这是从 pandas v0.24.0 引入的,替换了旧的 .values
方法。我们可以在 index
,series
和 dataframe
对象上定义 to_numpy
。
旧的 dataframe.values
具有不一致的行为,根据 pandasapi 文档,我们不建议使用它。但是,如果你使用的是旧版本,我们将研究此方法的例子。
另外一个不推荐使用的旧方法是 dataframe.as_matrix()
,请不要使用它!
我们还将介绍另一种使用 dataframe.to_records()
方法将给定的 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]]
可以通过以下方法使用 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]]
如果我们想在 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]]
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)
(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)]
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
pandas dataframe dataframe.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:python
-
dataframe.shift() 函数是将 dataframe 的索引按指定的周期数进行移位。
python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:python
-
python pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:python
-
pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 dataframe 中。
pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:python
-
本教程介绍了如何在 pandas 中使用 dataframe.merge()方法合并两个 dataframes。
pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:python
-
本教程介绍了如何使用 python 中的 loc 和 iloc 从 pandas dataframe 中过滤数据。
在 python 中将 pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:python
-
了解如何在 python 中将 pandas 系列日期时间转换为字符串