DataFrame,如果特定列值在DF1中,则在DF2的特定行中添加DF1的值

时间:2017-01-11 15:34:59

标签: python pandas

我一直在搜索SO和大熊猫的帮助,但找不到我要找的东西。

我有两个包含这些列的数据框:

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'并填充来自的值数据帧1“

有没有这样做?

2 个答案:

答案 0 :(得分:1)

您想使用df2作为基础,然后使用列'id'加入df1:

df2.join(df1.set_index('id'), 'id')

答案 1 :(得分:0)

试试这个:

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