如何根据列的值获取另一个数据帧值并设置为相应的字段

时间:2017-11-07 02:03:17

标签: python pandas

这是我的两个数据框,

df1 = pd.DataFrame([['@1','A',2],['@2','A',1],['@3','A',4],['@4','B',1],['@5','B',1],['@6','B',3],['@7','B',3],['@8','C',4]],columns=['key1','key2','value'])

  key1 key2  value
0   @1    A      2
1   @2    A      1
2   @3    A      4
3   @4    B      1
4   @5    B      1
5   @6    B      3
6   @7    B      3
7   @8    C      4

df2 = pd.DataFrame([['@5','B',None],['@7','B',None],['@6','B',None],['@3','A',None],['@6','B',None]],columns=['key1','key2','value'])

  key1 key2 value
0   @5    B  None
1   @7    B  None
2   @6    B  None
3   @3    A  None
4   @6    B  None

我知道我可以使用isin来选择df1的行,其中key1 + key2在df2中

df1[(df1['key1']+df1['key2']).isin(df2['key1']+df2['key2'])]

  key1 key2  value
2   @3    A      4
4   @5    B      1
5   @6    B      3
6   @7    B      3

但是如何将df1的['value']分配给df2,以便让df2

  key1 key2 value
0   @5    B  1
1   @7    B  3
2   @6    B  3
3   @3    A  4
4   @6    B  3

2 个答案:

答案 0 :(得分:2)

使用pd.DataFrame.merge

df2[['key1', 'key2']].merge(df1, 'left')

  key1 key2  value
0   @5    B      1
1   @7    B      3
2   @6    B      3
3   @3    A      4
4   @6    B      3

pd.DataFrame.join

keys = ['key1', 'key2']
df2[keys].join(df1.set_index(keys).value, on=keys)

  key1 key2  value
0   @5    B      1
1   @7    B      3
2   @6    B      3
3   @3    A      4
4   @6    B      3

假设您要更新df2,同时保持其他列不变。您可以update到位

keys = ['key1', 'key2']
df2.update(df2[keys].join(df1.set_index(keys).value, on=keys).value)

或创建副本

keys = ['key1', 'key2']
df2.assign(value=df2[keys].join(df1.set_index(keys).value, on=keys).value)

答案 1 :(得分:2)

或者您可以使用//// Sensitivity up //// function value_Up(){ sensitivityFlag = 1; } //// Sensitivity down //// function value_Down(){ sensitivityFlag = -1; } function sensitivity(x){ sens = 1*x/1000; switch (sensitivityFlag){ case -1: sensitivity_Down(); break case 1: sensitivity_Up(); break }

fillna