Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用索引列表从字典中获取值_Python_Python 3.x_Data Manipulation - Fatal编程技术网

Python 使用索引列表从字典中获取值

Python 使用索引列表从字典中获取值,python,python-3.x,data-manipulation,Python,Python 3.x,Data Manipulation,给出一个列表: 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

给出一个列表:

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


您可以使用
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)
使用熊猫:

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)

输出:int64索引([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]}
更容易:

df['vals']=list(filter(None,x))
df['idx']=df['vals'].apply(x.index)
举例:
  • 使用
    filter(None,x)
    过滤非0值,(
    None
    基本上不包含任何语句(或者不
    False

  • 然后使用pandas apply获取索引,基本上通过
    'vals'
    列,然后获取列表
    x

  • df['vals']=list(filter(None,x))
    df['idx']=df['vals'].apply(x.index)