Python技术迷

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

整理: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\n----------\n', info)  #convert the dataframe to a numpy array  arr = info.to_numpy()  print('\nNumpy Array\n----------\n', arr)
输出
DataFrame----------   x    y   z0  17  62  351  25  36  542  42  20  153  48  62  76
Numpy Array---------- [[17 62 35] [25 36 54] [42 20 15] [48 62 76]]
Image
 1
Image
热门推荐

Image