Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.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
数据帧中vlookup的python等价物_Python - Fatal编程技术网

数据帧中vlookup的python等价物

数据帧中vlookup的python等价物,python,Python,我有一个df df = {'a1': [2, 4, 7, 5, 6], 'a2': [A, B, C, D, A], 'a3': [4, 3, 2, 8, 7], 'x1': [2, 2, 4, 6, 4], 'x2': [2, 2, 2, 6, 7]} df = pd.DataFrame(df, index=range(0,5)) 还有一句格言: cost={} cost['A']=0.2 cost['B']=0.1 cost['C']=0.3 cos

我有一个df

df = {'a1': [2, 4, 7, 5, 6],
     'a2': [A, B, C, D, A],
     'a3': [4, 3, 2, 8, 7],
     'x1': [2, 2, 4, 6, 4],
     'x2': [2, 2, 2, 6, 7]}
df = pd.DataFrame(df, index=range(0,5))
还有一句格言:

cost={}
cost['A']=0.2
cost['B']=0.1
cost['C']=0.3
cost['D']=0.5
我希望在我的df中增加一列“成本”,以便成本列是基于a2列中相关信函的相关成本

所需的输出将是df本身:(如果我手动写出它!)

到目前为止,我的低效方法是:

df['cost']=df['a2']
for i in range(0,len(df.index),1):
    df['cost'][i]=cost[df['cost'][i]]
有人知道如何在没有循环的情况下做到这一点吗?
感谢使用您的
df
成本

df['cost'] = df['a2'].apply(cost.get)
这可能不会比
for
循环快多少,也许有更好的方法。 输出:

df['cost'] = df['a2'].apply(cost.get)
   a1 a2  a3  x1  x2  cost
0   2  A   4   2   2   0.2
1   4  B   3   2   2   0.1
2   7  C   2   4   2   0.3
3   5  D   8   6   6   0.5
4   6  A   7   4   7   0.2