Python Pandas 合并两个数据帧而不改变顺序

标签 python pandas dataframe

我有两个 pandas Dataframe,一个是 df1,形状 = (35,9),另一个是 df2,形状 = (12,9),我想要合并它们。

df2的行索引是:

RangeIndex(start=1, stop=13, step=1)

df1 的行索引为:

Int64Index([    2, 10021, 10022, 10023, 10024,     3, 10021, 10022, 10023,
        10024,     4, 10021, 10022, 10023, 10024,     5, 10021, 10022,
        10023, 10024,     6, 10021, 10022, 10023, 10024,     7, 10021,
        10022, 10023, 10024,     8, 10021, 10022, 10023, 10024],
       dtype='int64')

我想合并这两个数据帧,以便生成的数据帧具有以下索引:

Int64Index([1,2,10021,10022,10023,10024, 3, 10021, 10022, 10023,
        10024,     4, 10021, 10022, 10023, 10024,     5, 10021, 10022,
        10023, 10024,     6, 10021, 10022, 10023, 10024,     7, 10021,
        10022, 10023, 10024,     8, 10021, 10022, 10023, 10024, 9, 10, 11, 12],
       dtype='int64')

最佳答案

我认为您正在寻找外部联接:

import pandas as pd
idx1 = [    2, 10021, 10022, 10023, 10024,     3, 10021, 10022, 10023,
        10024,     4, 10021, 10022, 10023, 10024,     5, 10021, 10022,
        10023, 10024,     6, 10021, 10022, 10023, 10024,     7, 10021,
        10022, 10023, 10024,     8, 10021, 10022, 10023, 10024]
df1 = pd.DataFrame(data={'a': range(len(idx1))},
                   index=idx1)


df2 = pd.DataFrame(data={'b': range(1,13)},
                   index=range(1,13))

result_df = pd.merge(df1, df2, how='outer', left_index=True, right_index=True)
result_df.index
Int64Index([    1,     2,     3,     4,     5,     6,     7,     8,     9,
               10,    11,    12,    13, 10021, 10021, 10021, 10021, 10021,
            10021, 10021, 10022, 10022, 10022, 10022, 10022, 10022, 10022,
            10023, 10023, 10023, 10023, 10023, 10023, 10023, 10024, 10024,
            10024, 10024, 10024, 10024, 10024],
          dtype='int64')

关于Python Pandas 合并两个数据帧而不改变顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59699060/

相关文章:

r - 在 R 中,从 df 中采样 n 行,其中某个列具有非 NA 值(有条件地采样)

python - Pandas :减去两个数据帧时所有NaN

python - Pandas:将数据框中的列与为公共(public)变量创建的新列合并

python - 数据结构选择python

python - Pandas - 在数据帧 : ValueError: cannot reindex from a duplicate axis 中追加字符串

python - 在预先排序的 DataFrame 上使用 pandas groupby 的迭代顺序

python - Pandas 根据连接将一个数据框中的列添加到另一个数据框中

Python Pandas : fill a dataframe row by row

Python - 在没有 if 语句的情况下将数字转换为字母

python - 使用表单集前缀时缺少 ManagementForm 数据