将 Pandas DataFrame 转换为 NumPy 数组
要将PandasDataFrame转换为NumPy数组,我们可以使用to_numpy().
步骤
创建二维、大小可变、潜在异构的表格数据df。
打印输入数据帧。
使用打印给定数组的NumPy数组。df.to_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:\n", df print "DataFrame to numpy is:\n", df.to_numpy() print "DataFrame to numpy is:\n", 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]