python通过搜索字典替换值

时间:2017-10-17 09:37:10

标签: python dictionary

我是python的新生。最近,我遇到了一个非常简单的问题。首先,有一个字典缩写的字典,例如:

{'a':apple,'b':bread,'c':coke}

此外,还有一个数据框,其索引为{'a','b','c'},我想通过搜索字典来替换索引。结果将是

{'apple','bread','coke'}

事实上,我知道我可以通过访问每个项目来使用流通。但是,这种方法对于庞大的数据来说可能很糟糕。

所以我想知道我是否还有其他有效的方法可供使用?

3 个答案:

答案 0 :(得分:0)

如果您希望用其他元素替换它们,则必须访问每个元素。以下是关于如何在python中实现它的想法。

假设您的数据集看起来像这样:

d = {'a':'apple', 'b': 'bread', 'c':'coke'}
l = ['a', 'b', 'c']

你可以使用列表理解来做这样的事情:

# look in the dictionary for the value, 
# if it's there replace with the value, else let it be there as it is

l = [d[e] if e in d else e for e in l]

或使用地图:

l = map(lambda e: d[e] if e in d else e, l)

答案 1 :(得分:0)

我不认为有一种方法可以在不迭代元素的情况下替换值,但如果你想保持代码简单,你可以尝试这样的事情:

dict1 = {'a': 'apple','b': 'bread' ,'c':'coke'}
auxList = ['a', 'b', 'c']

auxList = [dict1.get(elem) for elem in auxList]

print(auxList)

结果是:

['apple', 'bread', 'coke']

或者您可以尝试:

auxList = list(map(lambda elem: dict1.get(elem), auxList))

结果将是:

['apple', 'bread', 'coke']

答案 2 :(得分:0)

回答panda的DataFrame -

import pandas as pd

a = ['a','b','c']
b = [[1,2,3],[4,5,6],[7,8,9]]
df = pd.DataFrame(index=a, data=b)   
dic = {'a':'apple','b':'bread','c':'coke'}
df
   0  1  2
a  1  2  3
b  4  5  6
c  7  8  9

通过dataframe索引获取字典值:

[dic.get(a) for a in df.index]
['apple', 'bread', 'coke']

设置索引:

df.set_index(keys=[[dic.get(a) for a in df.index]], inplace=True)
df
       0  1  2
apple  1  2  3
bread  4  5  6
coke   7  8  9
相关问题