【问题标题】:merging two dataframes with same rows and indexes in pandas在熊猫中合并两个具有相同行和索引的数据框
【发布时间】: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


【解决方案1】:

我会尝试:

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

也许

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

【讨论】:

  • 这个工作 pd.merge(df, df2, on=[0, 1]),只需要重命名列,谢谢!
【解决方案2】:

只要做:

df.merge(df2, on=1)

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

您的错误是仅通过索引进行合并,合并函数不知道两个数据中的第 1 列相等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-27
    • 2017-01-31
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    相关资源
    最近更新 更多