我有一個字典列表,所有字典都有相同的10個關鍵字。將字典列表轉換爲1D numpy數組
尋找一種簡潔的方式將其轉換爲10個1D numpy數組。效率不重要。
目前有20行代碼。
names = [x['name'] for x in fields]
names = np.asarray(names)
等
我有一個字典列表,所有字典都有相同的10個關鍵字。將字典列表轉換爲1D numpy數組
尋找一種簡潔的方式將其轉換爲10個1D numpy數組。效率不重要。
目前有20行代碼。
names = [x['name'] for x in fields]
names = np.asarray(names)
等
你可以使用嵌套列表理解:
[np.asarray([x[attribute] for x in fields]) for attribute in ['name', 'age', 'address']]
或字典理解:
{attribute:np.asarray([x[attribute] for x in fields]) for attribute in ['name', 'age', 'address']}
舉個例子:
>>> fields = [{'name': 'A', 'age': 25, 'address' : 'NYC'}, {'name': 'B', 'age': 32, 'address' : 'LA'}]
>>> [np.asarray([x[attribute] for x in fields]) for attribute in ['name', 'age', 'address']]
[array(['A', 'B'],
dtype='|S1'), array([25, 32]), array(['NYC', 'LA'],
dtype='|S3')]
>>> {attribute:np.asarray([x[attribute] for x in fields]) for attribute in ['name', 'age', 'address']}
{'age': array([25, 32]), 'name': array(['A', 'B'],
dtype='|S1'), 'address': array(['NYC', 'LA'],
dtype='|S3')}
要獲得在自動方式的屬性,你可以使用:
>>> fields[0].keys()
['age', 'name', 'address']
最後,熊貓可能是最合適的類型爲您的數據:
>>> pd.DataFrame(fields)
address age name
0 NYC 25 A
1 LA 32 B
這將是足夠快並且應該允許您在陣列列表上執行任何您想要執行的操作。
在括號中,'np.asarray([字段中的x [屬性]])'? – Zero
@ZEro:確實。謝謝 –
讓A
成爲詞典的輸入列表。
對於每個關鍵字每一行保持數據的2D陣列輸出 -
np.column_stack([i.values() for i in A])
樣品運行 -
In [217]: A # input list of 2 dictionaries, each with same 3 keywords
Out[217]:
[{'a': array([6, 8, 2]), 'b': array([7, 7, 3]), 'c': array([6, 6, 4])},
{'a': array([4, 4, 3]), 'b': array([7, 1, 6]), 'c': array([6, 1, 5])}]
In [244]: np.column_stack([i.values() for i in A])
Out[244]:
array([[6, 8, 2, 4, 4, 3], # key : a
[6, 6, 4, 6, 1, 5], # key : c
[7, 7, 3, 7, 1, 6]]) # key : b
# Get those keywords per row with `keys()` :
In [263]: A[0].keys()
Out[263]: ['a', 'c', 'b']
一個多個樣品遊程
In [245]: fields # sample from @Eric's solution
Out[245]:
[{'address': 'NYC', 'age': 25, 'name': 'A'},
{'address': 'LA', 'age': 32, 'name': 'B'}]
In [246]: np.column_stack([i.values() for i in fields])
Out[246]:
array([['25', '32'],
['A', 'B'],
['NYC', 'LA']],
dtype='|S21')
In [267]: fields[0].keys()
Out[267]: ['age', 'name', 'address']
*效率並不重要* ,出於任何特定的原因? – ZdaR
那麼,輸出將是二維數組還是一維數組列表? – Divakar
如果你使用Pandas,'pd.DataFrame(fields).T.values' – Zero