首页 > 行业资讯 > Pandas 教程-将Pandas DataFrame转换为Numpy数组

Pandas 教程-将Pandas DataFrame转换为Numpy数组

时间:2024-04-09 来源: 浏览:

Pandas 教程-将Pandas DataFrame转换为Numpy数组

点击关注 Python架构师
Python架构师

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 )

资源分享

点击领取:最全Python资料合集

示例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]]

 
热门推荐
  • 为什么很多企业明确不招外包?
  • Pandas 教程-Pandas DataFrame.where()
  • 干掉 Postman?测试接口直接生成API文档,这个文档工具真香!

下一条:返回列表
版权:如无特殊注明,文章转载自网络,侵权请联系cnmhg168#163.com删除!文件均为网友上传,仅供研究和学习使用,务必24小时内删除。
相关推荐