如何基于熊猫第一个数据框中的某些列值从第二个数据框中添加列值

时间:2018-10-24 10:18:11

标签: python pandas

我的第一个DataFrame是这样的:

def setBackground(color, texture):
  scn = bpy.context.scene
  scn.render.engine = 'CYCLES'
  scn.world.use_nodes = True
  wd = scn.world
  nt = bpy.data.worlds[wd.name].node_tree
  srcNode = nt.nodes.new(type=texture)
  #set color
  srcNode.color = color
  if "ShaderNodeAttribute" == texture:
    srcNode.attribute_name = 'color'
  #find location of Background node and position Grad node to the left
  backNode = nt.nodes['Background']
  srcNode.location.x = backNode.location.x-300
  srcNode.location.y = backNode.location.y
  #Connect color out of Grad node to Color in of Background node
  srcColOut = srcNode.outputs['Color']
  backColIn = backNode.inputs['Color']
  nt.links.new(srcColOut, backColIn)

setBackground((1,1,1), "ShaderNodeTexNoise")

我的第二个数据框是:

RowCol  Value_Pre
Key1 234
Key3 235
Key2 235
Key4 237

如何通过组合两个数据框来创建像下面的第三个数据框

RowCol  Value_Post
Key3 235
Key1 334
Key4 237
Key2 435

如何用Python开发此代码?

1 个答案:

答案 0 :(得分:1)

使用map

df1['Value_Post'] = df1['RowCol'].map(df2.set_index('RowCol')['Value_Post'])
print (df1)
  RowCol  Value_Pre  Value_Post
0   Key1        234         334
1   Key3        235         235
2   Key2        235         435
3   Key4        237         237

merge左连接,尤其是在必要时附加多个新列:

df = df1.merge(df2, on='RowCol', how='left')