我正在尝试使用numpy数组创建一个pandas数据框架。数据,索引和列数组都是numpy 'ndarray '(分别为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。narray对象没有属性'endswith'
当我打印print(df1.to_string())
时返回相同的错误,但如果我打印print(df1.values)
, print(df1.index)
或print(df1.columns)
,则返回预期的值。
我错过了什么吗?不可否认,我对使用Pandas还很陌生,但是我认为这个简单的示例应该可以很好地工作。
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
没有为数组定义。
index
和columns
都采用类似列表的属性(包括array
)。你不需要担心它们是矩阵中的"列"还是"行"(我认为这就是你使用元组的原因)。
你只想要一个数组…
>>> np.zeros(15)
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0.])
我认为如果源是np.zeros((100, 15))
和np.zeros ((15, 1))
,则需要ravel
用于创建index
和columns
的平坦数组:
index = np.zeros((100, 1)).ravel()
columns = np.zeros ((15, 1)).ravel()
但如果需要索引和列的默认值,只需使用DataFrame
构造函数- index
和columns
将设置为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
...
...