【发布时间】:2018-07-17 03:47:42
【问题描述】:
我正在尝试合并两个具有共同行索引和共同列 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
到目前为止,我尝试过合并:
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
与连接:
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
编辑:也许我不清楚,如果是这样,我很抱歉,我正在尝试将第二个数据集中的最后一列添加到结果中,所以我有相同的年份、月份、value1然后是 value2 列
【问题讨论】:
-
df.merge(df2, on=[0, 1])? -
首先,在您的示例中似乎没有名为 3 的列。我假设您正在尝试加入索引以及第 1 列和第 2 列。您尝试过
pd.merge(df,df2, on = [1,2])吗?您能否更明确地说明什么是列以及什么是索引? -
是什么阻止您在 concat 命令后删除第 4 列和第 5 列?使用 df1['new'] = df2.iloc[:, 2] 不是更容易吗?
-
您的问题陈述具有误导性:cols 0,1,2 是相同的,只有您的未命名列 3 各不相同。
-
好的,所以我要做的是将第二个数据集中的第 3 列添加为合并数据集中的第 4 列
标签: python pandas dataframe merge