所以你a
是一個列表的列表:
In [656]: a = [[{'col':i,'row':j} for i in range(9)] for j in range(9)]
In [657]: a
Out[657]:
[[{'col': 0, 'row': 0},
{'col': 1, 'row': 0},
{'col': 2, 'row': 0},
....
In [658]: len(a)
Out[658]: 9
In [659]: a[2][3]
Out[659]: {'col': 3, 'row': 2}
從創建一個數組:
In [660]: A=np.array(a, dtype=object)
In [661]: A.shape
Out[661]: (9, 9)
In [662]: A
Out[662]:
array([[{'row': 0, 'col': 0}, {'row': 0, 'col': 1}, {'row': 0, 'col': 2},
{'row': 0, 'col': 3}, {'row': 0, 'col': 4}, {'row': 0, 'col': 5},
In [663]: A[2,3]
Out[663]: {'col': 3, 'row': 2}
使用a[2][3]
和A[2,3]
訪問一個字典之間沒有太大的區別。兩者都包含指向相同字典的指針
In [664]: A[3,2]['value']=23 # add a key to one; see change in both places
In [666]: A[3,2]
Out[666]: {'col': 2, 'row': 3, 'value': 23}
In [667]: a[3][2]
Out[667]: {'col': 2, 'row': 3, 'value': 23}
我可以重塑A
, A1=A.reshape(3,27)
,但這不會影響列表嵌套a
。我可以「扁平化」兩種搭配:
In [671]: aflat=list(itertools.chain(*a)) # new list, same dict
In [672]: len(aflat)
Out[672]: 81
In [673]: A.ravel().shape # a view A.flatten() for copy
Out[673]: (81,)
我能找到與列表理解額外關鍵的字典之一:
In [674]: [a for a in aflat if len(a)==3]
Out[674]: [{'col': 2, 'row': 3, 'value': 23}]
In [675]: [a for a in A.ravel() if len(a)==3]
Out[675]: [{'col': 2, 'row': 3, 'value': 23}]
有時對象dtypes它可以執行有限數量的數組數學,但這取決於向下傳播到對象的操作。我想不出任何會用字典做的事情。
因此對於字典對象,使用嵌套列表和對象數組之間沒有太大區別。
數組索引通常的規則:
In [676]: idx=[2,3]
In [677]: A[idx] # (2,9) array of dict
Out[677]:
array([[{'row': 2, 'col': 0}, ...{'row': 3, 'col': 8}]], dtype=object)
In [678]: A[tuple(idx)] # 1 dict
Out[678]: {'col': 3, 'row': 2}
結構陣列的方法,使用fields
具有相同的名稱作爲您的字典鍵。
In [681]: dt=np.dtype([('col',int),('row',int)])
In [687]: S = np.array([[(i,j) for i in range(3)] for j in range(3)],dtype=dt)
In [688]: S.shape
Out[688]: (3, 3)
In [689]: S
Out[689]:
array([[(0, 0), (1, 0), (2, 0)],
[(0, 1), (1, 1), (2, 1)],
[(0, 2), (1, 2), (2, 2)]],
dtype=[('col', '<i4'), ('row', '<i4')])
In [691]: S[2,2]
Out[691]: (2, 2)
In [692]: S['col']
Out[692]:
array([[0, 1, 2],
[0, 1, 2],
[0, 1, 2]])
In [694]: S[0,2]['row']
Out[694]: 0
看看熊貓:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html#pandas.DataFrame –
謝謝!是否有可能熊貓超過2維?剛剛找到了一個很新的xarray。 – Wikunia
他們有'面板',讓你有三維數據:http://pandas.pydata.org/pandas-docs/stable/dsintro.html#panel。 AFAIK不支持超過3個維度。 –