Pandas 教程-将Pandas DataFrame转换为Numpy数组
Pandas 教程-将Pandas DataFrame转换为Numpy数组
gh_1d7504e4dee1
回复:python,领取Python面试题。分享Python教程,Python架构师教程,Python爬虫,Python编程视频,Python脚本,Pycharm教程,Python微服务架构,Python分布式架构,Pycharm注册码。
整理: python架构师
为了执行一些高级数学函数,我们可以将Pandas DataFrame转换为numpy数组。它使用DataFrame.to_numpy()函数。
DataFrame.to_numpy() 函数应用于DataFrame,返回numpy ndarray。
语法
DataFrame.to_numpy(dtype=
None
, copy=
False
)
参数
-
dtype :这是一个可选参数,将dtype传递给numpy.asarray()。
-
copy :它返回布尔值,其默认值为False。
它确保返回的值不是另一个数组上的视图。
返回值
它返回numpy.ndarray作为输出。
示例1
import
pandas
as
pd
pd.DataFrame({
"P"
: [
2
,
3
],
"Q"
: [
4
,
5
]}).to_numpy()
info = pd.DataFrame({
"P"
: [
2
,
3
],
"Q"
: [
4.0
,
5.8
]})
info.to_numpy()
info[
’R’
] = pd.date_range(
’2000’
, periods=
2
)
info.to_numpy()
array([[
2
,
4.0
, Timestamp(
’2000-01-01 00:00:00’
)],
[
3, 5.8, Timestamp(’2000-01-02 00:00:00’)
]], dtype=
object
)
资源分享
示例2
import
pandas as pd
#initializing the dataframe
info
= pd.DataFrame([[
17
,
62
,
35
],[
25
,
36
,
54
],[
42
,
20
,
15
],[
48
,
62
,
76
]],
columns=[
’x’
,
’y’
,
’z’
])
print(
’DataFrame
----------
’
,
info
)
#convert the dataframe to a numpy array
arr =
info
.to_numpy()
print(
’
Numpy Array
----------
’
, arr)
DataFrame
----------
x
y z
0
17 62 35
1
25 36 54
2
42 20 15
3
48 62 76
Numpy
Array
----------
[[17
62 35]
[25
36 54]
[42
20 15]
[48
62 76]]
-
2023年血糖新标准公布,不是3.9-6.1,快来看看你的血糖正常吗? 2023-02-07
-
2023年各省最新电价一览!8省中午执行谷段电价! 2023-01-03
-
GB 55009-2021《燃气工程项目规范》(含条文说明),2022年1月1日起实施 2021-11-07
-
PPT导出高分辨率图片的四种方法 2022-09-22
-
2023年最新!国家电网27家省级电力公司负责人大盘点 2023-03-14
-
全国消防救援总队主官及简历(2023.2) 2023-02-10
-
盘点 l 中国石油大庆油田现任领导班子 2023-02-28
-
我们的前辈!历届全国工程勘察设计大师完整名单! 2022-11-18
-
关于某送变电公司“4·22”人身死亡事故的快报 2022-04-26