为了执行一些高级数学函数,无涯教程可以将Pandas DataFrame转换为numpy数组。它使用DataFrame.to_numpy()函数。
DataFrame.to_numpy()函数应用于返回numpy ndarray的DataFrame。
DataFrame.to_numpy(dtype=None, copy=False)
它确保返回的值不是另一个数组上的视图。
它返回 numpy.ndarray 作为输出。
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)
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]]
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)