繁体   English   中英

使用float索引合并两个pandas数据帧

[英]Merge two pandas dataframes using float index

我有两个DataFrame有不同的列,但我想通过在行上对齐它们来合并它们。 也就是说,我说有两个dataFrames

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

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

我会暂时将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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM