Ben*_*ose 2 python dictionary numpy
我有一个 python 字典,其中所有值都是相同长度的数组。我希望能够通过元素编号提取这些值。
我有一本这样的字典:
dictionary = { 'key1': [1,2,3], 'key2': [4,5,6], 'key3': [7,8,9] }
Run Code Online (Sandbox Code Playgroud)
在调用参数 1 时,我想要这个输出:
[2,5,8]
Run Code Online (Sandbox Code Playgroud)
我拥有的最好的是
[dictionary.values()[0][1], dictionary.values()[1][1], dictionary.values()[2][1] ]
Run Code Online (Sandbox Code Playgroud)
因为
dictioinary.values()[:][1]
Run Code Online (Sandbox Code Playgroud)
即使 dictionary.values() 返回一个列表也不起作用。
或者将这些数据存储在二维数组中或使用 numpy 会更容易吗?我想使用字典,以便我可以通过键调用数据。
使用纯 Python,您可以使用列表理解:
In [106]: [dictionary[key][1] for key in ('key1', 'key2', 'key3')]
Out[106]: [2, 5, 8]
Run Code Online (Sandbox Code Playgroud)
(由于dict键是无序的,如果您想按该顺序访问对应于 'key1'、'key2'、'key3' 的值,您必须明确说明这些键,或者使用类似的东西sorted(dictionary.keys()))。
爬上便利的阶梯,您可以改用 NumPy。以下将字典转换为数组:
In [111]: arr = np.array([dictionary[key] for key in ('key1', 'key2', 'key3')]).T
In [112]: arr
Out[112]:
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
Run Code Online (Sandbox Code Playgroud)
选择数组的第二行:
In [113]: arr[1]
Out[113]: array([2, 5, 8])
Run Code Online (Sandbox Code Playgroud)
并选择第二列:
In [120]: arr[:, 1]
Out[120]: array([4, 5, 6])
Run Code Online (Sandbox Code Playgroud)
如果你想通过键名来引用列,那么你可以定义一个键映射:
In [126]: keymap = dict(zip(('key1', 'key2', 'key3'), range(3)))
In [127]: keymap
Out[127]: {'key1': 0, 'key2': 1, 'key3': 2}
In [128]: arr[:, keymap['key2']]
Out[128]: array([4, 5, 6])
Run Code Online (Sandbox Code Playgroud)
甚至更高的便利性,还有Pandas:Pandas DataFrames 支持基于列和/或索引(行)标签访问数据:
In [129]: import pandas as pd
In [130]: df = pd.DataFrame(dictionary)
In [131]: df
Out[131]:
key1 key2 key3
0 1 4 7
1 2 5 8
2 3 6 9
In [132]: df['key2']
Out[132]:
0 4
1 5
2 6
Name: key2, dtype: int64
In [133]: df.iloc[1] # Get the second row of the DataFrame
Out[133]:
key1 2
key2 5
key3 8
Name: 1, dtype: int64
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8702 次 |
| 最近记录: |