Python 使用浮动索引合并两个数据帧
我有两个具有不同列的Python 使用浮动索引合并两个数据帧,python,pandas,numpy,Python,Pandas,Numpy,我有两个具有不同列的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.DataFram
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
我想将df2
与df1
合并,以便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
我很欣赏任何关于如何有效解决这一问题的想法。我会暂时将df2的索引重新定义为其实际索引的四舍五入版本:
merged = (
df2.assign(idx=np.round(df2.index, 1)) # compute the rounded index
.reset_index(drop=True) # drop the existing index
.set_index('idx') # new, rounded index
.join(df1, how='right') # right join
.sort_index(axis='columns') # sort the columns
)
我得到:
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
既然你提到亲密
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
df1
是否保证每增加0.1行?如果是这样,您可以设置df2.index=df2.index.round(1)
,然后直接加入。谢谢!之所以接受,是因为这一答案直接比较了两个指数,而不是四舍五入。但是,如果您最终使用重复索引(看起来这就是我在实际应用程序中得到的结果),则这不起作用。我认为与@Paul H answer结合使用会起作用,但我做不到。现在我在pd.concat之前删除重复项。