【问题标题】:Merge two dataframes with special condition: rewrite how function of pandas.merge合并两个特殊条件的数据帧:重写 pandas.merge 的函数
【发布时间】:2021-05-02 06:45:52
【问题描述】:

我有两个共享相同索引的数据框。我想获得第三个数据帧,其中包含不是null 的行的第一个数据帧的数据以及来自第二个数据帧的行。如果可以选择重写pandas.mergehow 参数,我可以这样做。

也许有一种快速的方法可以做到这一点,目前还不明显。

编辑:数据帧中重叠的索引是相同的,但可能是某些索引出现在一个数据帧中而不是另一个数据帧中。这使得迭代索引成为一种代价高昂的解决方案。

这里是数据:df_1df_2 作为输入,df_3 作为输出。

df_1=
             0    1    2    3
bar   one  NaN  NaN  NaN  NaN
baz   two   AI   BI   CI   DI
foo   one   AJ   BJ   CJ   DJ
      two   AK   BK   CK   DK
qux   one   AL   BL   CL   DL
      two   AM   BM   CM   DM
other one  NaN  NaN  NaN  NaN

df_2=

          0   1   2   3
bar one  AA  BA  CA  DA
    two  AB  BB  CB  DB
baz one  AC  BC  CC  DC
    two  AD  BD  CD  DD
foo one  AE  BE  CE  DE
    two  AF  BF  CF  DF
qux two  AG  BG  CG  DG

df_3=

             0    1    2     3
bar   one   AA   BA   CA    DA
      two   AB   BB   CB    DB
baz   one   AC   BC   CC    DC
      two   AI   BI   CI    DI
foo   one   AJ   BJ   CJ    DJ
      two   AK   BK   CK    DK
qux   one   AL   BL   CL    DL
      two   AM   BM   CM    DM
other one  NaN  NaN  NaN  None

【问题讨论】:

  • 你能提供一些你有问题的数据吗?
  • @Pygirl 是的,但不仅在单个列上
  • 您也可以将其扩展为多列。我现在想不出更好的解决方案

标签: python pandas dataframe merge


【解决方案1】:

我只能想到这个:

col = df1.columns

def myfunc(x):
    if (df2.index.isin([x.name]).any() and pd.isnull(x[col]).all()):
        return pd.Series(df2.loc[x.name].values)
    else: 
        return pd.Series(x[col].values)
        
df1 = df1.apply(myfunc,axis=1)

df1:

            0   1   2   3
bar   one   AA  BA  CA  DA
baz   two   AI  BI  CI  DI
foo   one   AJ  BJ  CJ  DJ
two   AK    BK  CK  DK  None
qux   one   AL  BL  CL  DL
two   AM    BM  CM  DM  None
other one   NaN NaN NaN NaN

请随意修改此代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-18
    • 2019-12-01
    • 2018-08-21
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    相关资源
    最近更新 更多