将excel列提取到python数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22542442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:07:44  来源:igfitidea点击:

extract excel columns into python array

pythonarraysexcel

提问by user1681664

I want to extract excel columns (NOT rows) into python arrays of array. It has to be arrays, not dictionaries.

我想将 excel 列(不是行)提取到 python 数组数组中。它必须是数组,而不是字典。

The excel file looks like this:

excel文件如下所示:

     A    B    C
1   123  534  576
2   456  745  345
3   234  765  285

I want to bring this into python in the following format:

我想以以下格式将其带入python:

[[123,534,576],[456,745,345],[234,765,285]]

How would I do this? Thank you

我该怎么做?谢谢

采纳答案by user1681664

I figured it out.

我想到了。

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

回答by wwii

Use xlrd to load the data row-wise, then use zip to transpose it.

使用xlrd加载数据按行,然后使用压缩移调了。

>>> 
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> zip(*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> 

Use xlrd to load the data row-wise, use it to create a numpy array, then transpose it.

使用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]])
>>>

回答by David B.

If you're following the above comments and look into the xlrd package, can you try this and see if it works?

如果您按照上述评论并查看 xlrd 包,您可以尝试一下,看看它是否有效吗?

(based on what I found here: http://www.youlikeprogramming.com/2012/03/examples-reading-excel-xls-documents-using-pythons-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)

回答by user3245033

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

回答by Imad Salimi

Here's a yet simpler approach:

这是一个更简单的方法:

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)