首页 文章

Python:打印Pandas数据帧返回numpy.ndarray属性错误

提问于
浏览
2

我正在尝试使用numpy数组创建一个pandas数据帧 . 数据,索引和列数组都是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很新,但我认为这个简单的例子可以正常工作 .

2 回答

  • 1

    TL; DR

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

    细节

    您将一个元组参数传递给 np.zeros ,结果为 array of arrays .

    >>> 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 )的属性 . 你不要在矩阵中使用'column'或'row'(我认为这就是你使用元组的原因) .

    你只想要一个阵列......

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

    如果source是 np.zeros((100, 15))np.zeros ((15, 1)) ,我认为你需要ravel用于创建 indexcolumns 的flatten数组数组:

    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
    ...
    ...
    

相关问题