gpt4 book ai didi

python - 使用 float 索引合并两个 Pandas 数据帧

转载 作者:太空宇宙 更新时间:2023-11-03 14:46:55 25 4
gpt4 key购买 nike

我有两个具有不同列的 DataFrame,但我想通过在行上对齐它们来合并它们。也就是说,假设我有这两个数据框

df1 = pd.DataFrame(np.arange(12).reshape(6, 2), index=np.arange(6)*0.1, columns=['a', 'b'])

df1
a b
0.0 0 1
0.1 2 3
0.2 4 5
0.3 6 7
0.4 8 9
0.5 10 11

df2 = pd.DataFrame(np.arange(8).reshape(4, 2), index=[0.07, 0.21, 0.43, 0.54], columns=['c', 'd'])

df2
c d
0.07 0 1
0.21 2 3
0.43 4 5
0.54 6 7

我想将 df2df1 合并,这样 df2 的行与 `df1 的最近邻索引对齐。最终结果将是:

      a   b   c    d
0.0 0 1 NaN NaN
0.1 2 3 0 1
0.2 4 5 2 3
0.3 6 7 NaN NaN
0.4 8 9 4 5
0.5 10 11 6 7

我很欣赏有关如何有效解决此问题的任何想法。

最佳答案

既然你提到close

df2.index=[min(df1.index, key=lambda x:abs(x-y)) for y in df2.index]
pd.concat([df1,df2],1)
Out[535]:
a b c d
0.0 0 1 NaN NaN
0.1 2 3 0.0 1.0
0.2 4 5 2.0 3.0
0.3 6 7 NaN NaN
0.4 8 9 4.0 5.0
0.5 10 11 6.0 7.0

关于python - 使用 float 索引合并两个 Pandas 数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48605598/

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