将 Pandas DataFrame 转换为 NumPy 数组
pandasserver side programmingprogramming更新于 2024/9/29 3:34:00
要将 Pandas DataFrame 转换为 NumPy 数组,我们可以使用 to_numpy()。
步骤
创建一个二维、大小可变、可能异构的表格数据 df。
打印输入 DataFrame。
使用 df.to_numpy() 打印给定数组的 NumPy 数组。
使用 df['x'].to_numpy() 打印给定数组的特定列的 NumPy 数组。
示例
import pandas as pd df = pd.DataFrame( { "x": [5, 2, 1, 9], "y": [4, 1, 5, 10], "z": [4, 1, 5, 0] } ) print "Input DataFrame is:
", df print "DataFrame to numpy is:
", df.to_numpy() print "DataFrame to numpy is:
", df['x'].to_numpy()
输出
Input DataFrame is: x y z 0 5 4 4 1 2 1 1 2 1 5 5 3 9 10 0 DataFrame to numpy is: [[ 5 4 4] [ 2 1 1] [ 1 5 5] [ 9 10 0]] DataFrame to numpy is: [5 2 1 9]