[英]Pandas dataframe create a new column based on columns of other dataframes
So I have these two df's: 所以我有这两个df:
df A: df答:
ID TYPE
1 A
2 B
3 C
4 A
5 C
df B: df B:
TYPE MEASURE
A 0.3
B 0.4
C 0.5
What I would like to do is add a third column to df A based on the correspondence of df B regarding TYPE
: 我想要做的是根据关于
TYPE
的df B的对应关系向df A添加第三列:
ID TYPE MEASURE
1 A 0.3
2 B 0.4
3 C 0.5
4 A 0.3
5 C 0.5
I tried this code: 我试过这段代码:
def operation (row):
RESULT=B.loc[titlevar['TYPE'] == row['TYPE'] ][['MEASURE']].values
return RESULT
A['MEASURE'] = A.apply (lambda row: operation (row),axis=1)
But I think I am making more mistakes. 但我认为我犯了更多错误。 Hopefully somebody can help me.
希望有人可以帮助我。 Thanks in advance.
提前致谢。
You can use map for this 你可以使用map来做到这一点
dfA['MEASURE'] = dfA['TYPE'].map(dfB.set_index('TYPE')['MEASURE'])
dfA: DFA:
ID TYPE MEASURE
0 1 A 0.3
1 2 B 0.4
2 3 C 0.5
3 4 A 0.3
4 5 C 0.5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.