gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:35:15 25 4
gpt4 key购买 nike

我有两个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com