将Excel列提取到Python数组中
我想把Excel里的列(不是行)提取到Python的数组中,必须是数组,而不是字典。
这个Excel文件长这样:
A B C
1 123 534 576
2 456 745 345
3 234 765 285
我想把它导入到Python中,格式如下:
[[123,534,576],[456,745,345],[234,765,285]]
我该怎么做呢?谢谢!
6 个回答
0
这段代码是用来做某些操作的,但具体的功能和效果需要根据上下文来理解。通常情况下,代码块里会包含一些指令或者逻辑,用来处理数据或者实现特定的功能。
如果你看到这样的代码块,通常意味着这里有一些重要的代码需要关注。理解这些代码的作用,可以帮助你更好地掌握编程的基本概念。
记住,编程就像是给计算机下指令,你需要清楚每一行代码的意思,以及它们是如何一起工作的。
import csv
array = []
with open(* insert file directory here*) as fin:
reader = csv.reader(fin)
rows = [row for row in reader]
for row in rows:
j = 0
arr = []
for i = 0 < 3:
arr[i] = row[i]
array[j] = arr
j = j + 1
1
使用xlrd来按行加载数据,然后用zip来转置数据。
>>>
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> zip(*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>>
使用xlrd按行加载数据,接着用它创建一个numpy数组,然后进行转置。
>>> import numpy
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> z = numpy.array(a)
>>> z
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> z.transpose()
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
>>>
2
如果你按照上面的评论去了解一下xlrd这个包,可以试试这个方法,看看能不能成功。
(这个是我在这里找到的:http://www.youlikeprogramming.com/2012/03/examples-reading-excel-xls-documents-using-pythons-xlrd/)
import xlrd
workbook = xlrd.open_workbook('my_workbook.xls')
worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows - 1
curr_row = 0
#creates an array to store all the rows
row_array = []
while curr_row < num_rows:
row = worksheet.row(curr_row)
row_array += row
curr_row += 1
print(row_array)
13
这里有一个更简单的方法:
import xlrd
book = xlrd.open_workbook('your.xlsx')
sheet = book.sheet_by_name('example')
data = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in range(sheet.nrows)]
# Profit !
print(data)
0
我搞明白了。
import csv
cr = csv.reader(open("temp.csv","rb"))
arr = range(100) # adjust to needed
x = 0
for row in cr:
arr[x] = row
x += 1
print(arr[:22]) # adjust to needed