如何使用“values”atribute从数行日期框创建numpy数组?

2024-10-08 21:24:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个日期框架:

    TV  Radio   Newspaper   Sales
1   230.1   37.8    69.2    22.1
2   44.5    39.3    45.1    10.4
3   17.2    45.9    69.3    9.3
4   151.5   41.3    58.5    18.5
5   180.8   10.8    58.4    12.9

我需要创建两个NumPy数组。其中一个包含Sales行内容,另一个包含TVRadioNewspaper行。你知道吗

import numpy as np
first_arr = np.array(myDateFrame['Sales'].values) #It works
second_arr = np.array(myDateFrame['TV', 'Radio', 'Newspaper']) #It doesn't work

它给出以下错误:

error: KeyError: ('TV', 'Radio', 'Newspaper')

我哪里出错了?你知道吗


Tags: importnumpy框架内容npit数组tv
2条回答

你可以做:

>>> myDateFrame[['TV',  'Radio',  'Newspaper']].values
array([[ 230.1,   37.8,   69.2],
       [  44.5,   39.3,   45.1],
       [  17.2,   45.9,   69.3],
       [ 151.5,   41.3,   58.5],
       [ 180.8,   10.8,   58.4]])

不需要调用np.array()。属性values已经是NumPy数组。你知道吗

还要注意双方括号[['TV', 'Radio', 'Newspaper']].您需要将多个列名作为列表提供,而不是作为单个参数提供。你知道吗

我将使用as_matrix()方法:

DataFrame.as_matrix(columns=None)

Convert the frame to its Numpy-array representation.

相关问题 更多 >

    热门问题