[英]get values from a dictionary using a list of indexes
給出一個清單:
x = [0.0, 0.87, 0.0, 0.0, 0.0, 0.32, 0.46, 0.0, 0.0, 0.10, 0.0, 0.0]
我想所有的不為0的值的索引,並將其存儲在d['inds']
然后,使用索引以d['inds']
經過列表x
和獲取值。 所以我會得到類似的東西:
d['inds'] = [1, 5, 6, 9]
d['vals'] = [0.87, 0.32, 0.46, 0.10]
我已經使用了索引:
d['inds'] = [i for i,m in enumerate(x) if m != 0]
但我不知道如何得到d['vals']
d['vals'] = [x[i] for i in d['inds']]
更好的是,同時做兩件事:
vals = []
inds = []
for i,v in enumerate(x):
if v!=0:
vals.append(v)
inds.append(i)
d['vals']=vals
d['inds']=inds
要么
import numpy as np
d['inds'],d['vals'] = np.array([(i,v) for i,v in enumerate(x) if v!=0]).T
你可以使用numpy
,它的索引功能是專為這樣的任務設計的:
import numpy as np
x = np.array([0.0, 0.87, 0.0, 0.0, 0.0, 0.32, 0.46, 0.0, 0.0, 0.10, 0.0, 0.0])
x[x!=0]
Out: array([ 0.87, 0.32, 0.46, 0.1 ])
如果你仍然對指數感興趣:
np.argwhere(x!=0)
Out:
array([[1],
[5],
[6],
[9]], dtype=int64)
你可以使用dict理解:
m = {i:j for i,j in enumerate(x) if j!=0}
list(m.keys())
Out[183]: [1, 5, 6, 9]
list(m.values())
Out[184]: [0.87, 0.32, 0.46, 0.1]
如果你想保存在一個字典d
,那么你可以這樣做:
d = {}
d['vals']=list(m.values())
d['ind']=list(m.keys())
d
{'vals': [0.87, 0.32, 0.46, 0.1], 'ind': [1, 5, 6, 9]}
使用熊貓:
x = [0.0, 0.87, 0.0, 0.0, 0.0, 0.32, 0.46, 0.0, 0.0, 0.10, 0.0, 0.0]
import pandas as pd
data = pd.DataFrame(x)
inds = data[data[0]!=0.0].index
print(inds)
輸出:Int64Index([1,5,6,9],dtype ='int64')
更容易:
df['vals']=list(filter(None,x))
df['idx']=df['vals'].apply(x.index)
使用filter(None,x)
過濾非0值,( None
基本上沒有語句(或不是False
)
然后使用pandas申請獲取索引基本上通過'vals'
列然后獲取列表中的值索引x
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.