![](/img/trans.png)
[英]Update a dataframe(df1) column with value from another dataframe(df2) column when a key column in df1 matches to multiple columns in df2
[英]DataFrame, adding value from DF1 in specific row in DF2 if specific columns value is in DF1
我一直在SO和熊猫的帮助下进行大量搜索,但找不到我想要的东西。
我有2个数据框与这些列:
Index([u'id', u'date', u'heure', u'titre'], dtype='object')
Index([u'article', u'id', u'type', u'rubrique', u'source', u'rebond_global',
u'chargement_global', u'visites_global'],
dtype='object')
我希望能够做的是保留第二个数据,并使用“ id”作为键添加包含在第一个数据帧中的数据。
我最终的DataFrame总是让我感觉像是做了一个追加并添加了新列。
这是我尝试过的其他方法:
加盟方法:
df1.set_index('id').join(df2.set_index('id'))
合并方法:
pd.merge(df1, df2, how='outer', on='id')
在某种程度上,我正在尝试做的事情类似于“如果来自Dataframe 1的id在DataFrame 2中,然后在DataFrame 2中创建列'date','heure'和'titre'并填充Dataframe 1中的值”
反正有这样做吗?
您要使用df2作为基础,然后使用“ id”列加入df1:
df2.join(df1.set_index('id'), 'id')
尝试这个:
merged = pd.merge(left=df1[["id", "date", "heure", "titre"]], right=df2, on="id", how="inner")
编辑:完整示例:
df1 = pd.DataFrame({
"id": [1, 2, 3, 4],
"date": [10, 20, 30, 40],
"heure": ["h1", "h2", "h3", "h4"],
"titre": ["t1", "t2", "t3", "t4"]
})
df2 = pd.DataFrame({
"id": [1, 2, 3, 5],
"article": ["a1", "a2", "a3", "a5"]
})
merged = pd.merge(left=df1[["id", "date", "heure", "titre"]], right=df2, on="id", how="inner")
print "DF1:\n", df1
print "DF2:\n", df2
print "Merged:\n", merged
印刷品:
DF1:
date heure id titre
0 10 h1 1 t1
1 20 h2 2 t2
2 30 h3 3 t3
3 40 h4 4 t4
DF2:
article id
0 a1 1
1 a2 2
2 a3 3
3 a5 5
Merged:
id date heure titre article
0 1 10 h1 t1 a1
1 2 20 h2 t2 a2
2 3 30 h3 t3 a3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.