Pandas DataFrame转Numpy数组

Pandas DataFrame转Numpy数组 首页 / Pandas入门教程 / Pandas DataFrame转Numpy数组

为了执行一些高级数学函数,无涯教程可以将Pandas DataFrame转换为numpy数组。它使用DataFrame.to_numpy()函数。

DataFrame.to_numpy()函数应用于返回numpy ndarray的DataFrame。

语法

DataFrame.to_numpy(dtype=None, copy=False)

参数

  • dtype - 这是一个可选参数,它将dtype传递给numpy.asarray()。
  • copy   - 它返回具有默认值 False 的布尔值。

它确保返回的值不是另一个数组上的视图。

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/pandas/convert-pandas-dataframe-to-numpy-array.html

来源:LearnFk无涯教程网

返回值

它返回 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
#初始化数据框
info = pd.DataFrame([[17, 62, 35],[25, 36, 54],[42, 20, 15],[48, 62, 76]],
columns=['x', 'y', 'z'])
print('DataFrame\n----------\n', info)
#将数据框转换为 numpy 数组
arr = info.to_numpy()
print('\nNumpy Array\n----------\n', 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]]

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

深入浅出gRPC -〔李林锋〕

持续交付36讲 -〔王潇俊〕

浏览器工作原理与实践 -〔李兵〕

跟月影学可视化 -〔月影〕

重学线性代数 -〔朱维刚〕

陈天 · Rust 编程第一课 -〔陈天〕

Spring Cloud 微服务项目实战 -〔姚秋辰(姚半仙)〕

李智慧 · 高并发架构实战课 -〔李智慧〕

Vue 3 企业级项目实战课 -〔杨文坚〕

好记忆不如烂笔头。留下您的足迹吧 :)