简体   繁体   中英

Python list comprehension to populate 2D array from excel data only gives 1 column

Python 3.5 on Windows. I have a 9x2 range in Excel that I want to read into an array in Python.

Excel range data:

2             2
0.833333333   1
2.166666667   2
0             0
1             0
1             1
1.5           1.166666667
0.833         1.333
1.667         1.333

Python code:

import openpyxl   
import numpy

# physicians

physicians = ['DrA', 'DrB']

# activities
activities = ['Admin1', 'Frac2', 'Spec3', 'Fleb4', 'Latr5', 'Endo6', 'Surg7', 'Surg8',
 'Noth9', 'Annl10']

wb = openpyxl.load_workbook('m_a_j2pasted.xlsx')
type = wb
sheet = wb.get_sheet_by_name('sheet_mean_a_j')
M = [[sheet.cell(row=rows, column=cols).value for rows in range(1, len(activities))] for cols in range(1, len(physicians))]

M = numpy.array(M)
numpy.transpose(M)
print(M)

print(M)
out:
[[ 2.        ]
 [ 0.83333333]
 [ 2.16666667]
 [ 0.        ]
 [ 0.5       ]
 [ 0.5       ]
 [ 1.5       ]
 [ 0.83333333]
 [ 1.66666667]]

Now how do I get the 2nd column in there? I've also tried this way:

M = []
for rows in range(1, len(activities)):   
    values = []
    for cols in range(1, len(physicians)):
        values.append(sheet.cell(row=rows, column=cols).value)
    M.append(values)

Same thing.

Thanks

You are trying to index an uninitialized array first initialize it

w, h = 8, 5. Matrix = [[0 for x in range(w)] for y in range(h)] #initializing

Matrix[0][6] = 3 #input value or values through a loop

print Matrix[0][6] #prints the element or elements

In your case initialize DrA,DrB = 50,50. physicians = ['DrA', 'DrB']

Read up list comprehension in python

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM