获取数据帧1的索引到数据帧2

时间:2018-05-29 18:51:38

标签: python pandas dataframe

我有2个数据帧

Dataframe 1

annualGrammy

Dataframe2

AnnualGrammy Song

如果annualGrammy匹配,我想将Dataframe 2中Dataframe 1的索引作为新列。我需要合并吗?

2 个答案:

答案 0 :(得分:1)

假设你有

df1 = df1 = pd.DataFrame({"annualGrammy":[11,12,13,14,15,16,17,18]}, index=["i1","i2", "i3","i4","i5","i6","i7","i8"])
df2 = pd.DataFrame({"annualGrammy":[11,16,17,110,111], "song": ["a","b","c","d","e"]})

这样

df1.reset_index()

    annualGrammy    index
0   11              i1
1   12              i2
2   13              i3
3   14              i4
4   15              i5
5   16              i6
6   17              i7
7   18              i8

df2

    annualGrammy    song
0   11              a
1   16              b
2   17              c
3   110             d
4   111             e

您可以使用how="left"进行合并,以跟踪df1上的索引:

pd.merge(df1, df2, on="annualGrammy", how="left")

    index   annualGrammy    song
0   i1      11              a
1   i2      12              NaN
2   i3      13              NaN
3   i4      14              NaN
4   i5      15              NaN
5   i6      16              b
6   i7      17              c
7   i8      18              NaN

所有NaN都是ag中不匹配的值。您可以删除它们以仅获取重要的值

pd.merge(df1, df2, on="annualGrammy", how="left").dropna()

    annualGrammy    index   song
0   11              i1      a
5   16              i6      b
6   17              i7      c

答案 1 :(得分:0)

如果annualGrammy中的df1是唯一的,您还可以使用mapdf2中创建新列。使用RafaelC提供的数据

import pandas as pd

dct = pd.Series(df1.index.values, df1.annualGrammy.values).to_dict()
df2['index'] = df2.annualGrammy.map(dct)
df2 = df2.dropna()

df2现在

   annualGrammy song index
0            11    a    i1
1            16    b    i6
2            17    c    i7