在pandas中合并两个具有相同行和索引的数据帧

时间:2018-02-07 00:00:23

标签: python pandas dataframe merge

我正在尝试合并两个具有公共行索引和公共列0,1,2但不同列3的pandas数据帧,因此生成的数据帧包含两个列:

第一个数据帧:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 817 entries, 0 to 816
Data columns (total 3 columns):
0    817 non-null int64
1    817 non-null int64
2    817 non-null float64
dtypes: float64(1), int64(2)
memory usage: 19.2 KB


0   1       2
0   1950    1   -0.060310
1   1950    2   0.626810
2   1950    3   -0.008128
3   1950    4   0.555100
4   1950    5   0.071577

第二个数据帧:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 817 entries, 0 to 816
Data columns (total 3 columns):
0    817 non-null int64
1    817 non-null int64
2    817 non-null float64
dtypes: float64(1), int64(2)
memory usage: 19.2 KB

0   1       2
0   1950    1   0.92
1   1950    2   0.40
2   1950    3   -0.36
3   1950    4   0.73
4   1950    5   -0.59

到目前为止,我尝试使用merge:

pd.merge(df, df2, left_index=True, right_index=True, how='outer')

但结果不是我所期望的:

    0_x     1_x     2_x     0_y     1_y     2_y
0   1950    1   -0.060310   1950    1   0.92
1   1950    2   0.626810    1950    2   0.40
2   1950    3   -0.008128   1950    3   -0.36
3   1950    4   0.555100    1950    4   0.73
4   1950    5   0.071577    1950    5   -0.59

用concat:

pd.concat([df, df2], axis=1, ignore_index=True).head()


0   1       2       3       4       5
0   1950    1   -0.060310   1950    1   0.92
1   1950    2   0.626810    1950    2   0.40
2   1950    3   -0.008128   1950    3   -0.36
3   1950    4   0.555100    1950    4   0.73
4   1950    5   0.071577    1950    5   -0.59

我期待像

这样的东西
0   1       2       3     
0   1950    1   -0.060310    0.92
1   1950    2   0.626810     0.40
2   1950    3   -0.008128    -0.36
3   1950    4   0.555100     0.73
4   1950    5   0.071577     -0.59

编辑:也许我不清楚,如果是这样,我道歉,我正在尝试添加第二个数据集中的最后一列,因此我有相同的年份,月份,值1然后是value2列

2 个答案:

答案 0 :(得分:2)

我会尝试:

pd.merge(df, df2, on=['0', '1'])

也许

pd.merge(df, df2, on=[0,1]

答案 1 :(得分:0)

只是做:

df.merge(df2, on=1)

一旦它们具有相同的索引,您就不需要添加索引列。默认情况下它可以是内连接。

您的错误只是通过索引进行合并,合并功能并不知道两列数据中的列1相等。

相关问题