如何使用 pandas 将 excel 文件数据转换为 numpy 数组?
How to convert an excel file data into numpy array using pandas?
我是 keras 库的新手,也是 Python。我正在尝试使用 pandas 导入一个 excel 文件,并使用 pandas 的 as_matrix()
函数将其转换为 numpy.ndarray
。但它似乎错误地读取了我的文件。就像我在 Excel 文件中有一个 90x1049 的数据集。但是当我试图将它转换成 numpy 数组时,它读取我的数据为 89x1049。我正在使用以下代码,但它不起作用:
training_data_x = pd.read_excel("/home/workstation/ANN/new_input.xlsx")
X_train = training_data_x.as_matrix()
可能发生的情况是您的 Excel 文件没有 header 行,因此 pandas.read_excel
消耗了您的第一个数据行。
我尝试创建一个包含
的 xlsx
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
7 8 9
8 9 10
9 10 11
10 11 12
阅读结果
In [3]: df = pandas.read_excel('test.xlsx')
In [4]: df
Out[4]:
1 2 3
0 2 3 4
1 3 4 5
2 4 5 6
3 5 6 7
4 6 7 8
5 7 8 9
6 8 9 10
7 9 10 11
8 10 11 12
可以看出,第一个数据行已被用作列的标签。
为避免将第一个数据行消耗为 headers,将 header=None
传递给 read_excel
。有趣的是,documentation 之前没有提到这个用法,但自从:
header : int, list of ints, default 0
Row (0-indexed) to use for the column labels of the parsed DataFrame. If a list of integers is passed those row positions will be combined into a MultiIndex
. Use None if there are no headers.
如果您没有 header,请尝试以下操作:
training_data = pd.read_excel("/home/workstation/ANN/new_input.xlsx", header=None)
X_train = training_data_x.as_matrix()
另请参阅 previous question 的答案。
我是 keras 库的新手,也是 Python。我正在尝试使用 pandas 导入一个 excel 文件,并使用 pandas 的 as_matrix()
函数将其转换为 numpy.ndarray
。但它似乎错误地读取了我的文件。就像我在 Excel 文件中有一个 90x1049 的数据集。但是当我试图将它转换成 numpy 数组时,它读取我的数据为 89x1049。我正在使用以下代码,但它不起作用:
training_data_x = pd.read_excel("/home/workstation/ANN/new_input.xlsx")
X_train = training_data_x.as_matrix()
可能发生的情况是您的 Excel 文件没有 header 行,因此 pandas.read_excel
消耗了您的第一个数据行。
我尝试创建一个包含
的 xlsx1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
7 8 9
8 9 10
9 10 11
10 11 12
阅读结果
In [3]: df = pandas.read_excel('test.xlsx')
In [4]: df
Out[4]:
1 2 3
0 2 3 4
1 3 4 5
2 4 5 6
3 5 6 7
4 6 7 8
5 7 8 9
6 8 9 10
7 9 10 11
8 10 11 12
可以看出,第一个数据行已被用作列的标签。
为避免将第一个数据行消耗为 headers,将 header=None
传递给 read_excel
。有趣的是,documentation 之前没有提到这个用法,但自从:
header : int, list of ints, default 0
Row (0-indexed) to use for the column labels of the parsed DataFrame. If a list of integers is passed those row positions will be combined into a
MultiIndex
. Use None if there are no headers.
如果您没有 header,请尝试以下操作:
training_data = pd.read_excel("/home/workstation/ANN/new_input.xlsx", header=None)
X_train = training_data_x.as_matrix()
另请参阅 previous question 的答案。