【问题标题】:Python: Printing Pandas dataframe returns numpy.ndarray Attribute errorPython:打印 Pandas 数据框返回 numpy.ndarray 属性错误
【发布时间】:2017-03-13 06:05:12
【问题描述】:

我正在尝试使用 numpy 数组创建熊猫数据框。 数据、索引和列数组都是 numpy 'ndarrays'(分别为 2D、1D 和 1D)并且在本示例中都是 float64。

import pandas as pd
import numpy as np

data = np.zeros((100, 15))
index = np.zeros((100, 1))
columns = np.zeros ((15, 1))

df1 = pd.DataFrame(data=data, index=index, columns=columns)
print(df1)

当我打印 df1 时,我得到了这个我无法解决的属性错误:

AttributeError: 'numpy.ndarray' 对象没有属性 'endswith'

当我打印print(df1.to_string()) 时返回相同的错误,但如果我打印print(df1.values)print(df1.index)print(df1.columns),则会返回预期的值。

我在这里遗漏了什么吗?诚然,我对使用 Pandas 还很陌生,但我认为这个简单的例子可以正常工作。

【问题讨论】:

  • 感谢 jezrael 和 rmharrison - 这两个答案都帮助解决了我的问题。

标签: python pandas numpy dataframe


【解决方案1】:

TL;DR

>>> index = np.zeros(100)
>>> columns = np.zeros (15)

详情

您将一个元组参数传递给np.zeros,这会产生一个数组数组

>>> np.zeros((15,1))
array([[ 0.],
   [ 0.],
   [ 0.],
   [ 0.],
   [ 0.],
   [ 0.],
   [ 0.],
   [ 0.],
   [ 0.],
   [ 0.],
   [ 0.],
   [ 0.],
   [ 0.],
   [ 0.],
   [ 0.]])

您会收到错误,因为 i) 每个元素都是一个数组,并且 ii) endswith 没有为数组定义。

indexcolumns 都采用类似列表(包括 array)的属性。您无需担心它们是矩阵中的“列”还是“行”(我想这就是您使用元组的原因)。

你只需要一个数组...

>>> np.zeros(15)
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
    0.,  0.])

【讨论】:

    【解决方案2】:

    如果源是np.zeros((100, 15))np.zeros ((15, 1)),我认为您需要ravel 来创建indexcolumns 的扁平数组:

    index = np.zeros((100, 1)).ravel()
    columns = np.zeros ((15, 1)).ravel()
    

    但如果需要索引和列的默认值,只需使用 DataFrame 构造函数 - indexcolumns 将设置为 np.arange(n),因为没有索引信息和列标签:

    df1 = pd.DataFrame(data=data)
    print (df1)
    
         0    1    2    3    4    5    6    7    8    9    10   11   12   13   14
    0   0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
    1   0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
    2   0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
    3   0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
    4   0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
    5   0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
    ...
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-07
      • 2017-03-06
      • 2013-03-18
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 2015-02-12
      相关资源
      最近更新 更多