[英]Having trouble with lists and matrix using xlrd and python
所以我的問題是采用幾個長矢量(每個長15000行)並出現:
Origin Destination Distance
以及列中的相應值。 但是我想使用Python和xlrd包將這些轉換為具有
Destination1 Destination2
Origin1 Distance11 Distance12
Origin2 Distance21 Distance22
等等。
到目前為止,我嘗試過的是:
matrix ={}, i=0, list3 = [], list1 = []
for row in range(orksheet.nrows):
matrix[i] = {}
cell = worksheet.cell(row,2)
distance = cell.value
if float(distance) < 25000:
list1 = [int(worksheet.cell_value(row,0))]
list3 = list3.append(list1)
list2 = [int(worksheet.cell_value(row,1))]
for l in list1:
for j in list2:
matrix[l, j]=math.ceil(worksheet.cell_value(row,2))
i+=1
這有點奏效。 當我使用print(l,j,matrix [l,j]
在l和j的循環中,我得到了所需的值。 但是,使用print(matrix)會給出(常規,即類似的輸出,但具有相應的值)輸出:
(Origin, Destination): Distance and sometimes: distance: {}, distance: {},
等等。
我已經意識到問題出在矩陣上。 我不明白為什么打印出來的照片與我認為與列表有關? list1和list2有len 1,這對我來說似乎很奇怪。 我嘗試使用list3追加list1,但它也得到len 1。
問候,
對於數據處理任務,我不能推薦更多熊貓 。
例如,您在大熊貓中尋求的操作稱為ivot :
In [11]: df = pd.DataFrame({'origin': list('aabbccdd'), 'destination': ['d1', 'd2'] * 4, 'distance': np.arange(8)})
In [12]: df
Out[12]:
destination distance origin
0 d1 0 a
1 d2 1 a
2 d1 2 b
3 d2 3 b
4 d1 4 c
5 d2 5 c
6 d1 6 d
7 d2 7 d
In [13]: df.pivot('origin', 'destination', 'distance')
Out[13]:
destination d1 d2
origin
a 0 1
b 2 3
c 4 5
d 6 7
要讀取實際的excel文件,有pandas.read_excel ,AFAIR在后台使用xlrd:
df = read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA'])
在文檔中還有更多內容可以找到
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.