连接和分组填充 NaN 值

Concatenate and group-wise filling NaN values

我有这个数据框:

df:
companycode    name    address    A     B     C     ...
1234           asd     qwe,56     Tyh   123   923
1234           asd     qwe,56     Zfhs  4828  01992
6472           yui     iop,56     Retgh 8484  8484
...

我还有一个看起来像这样的:

df2:
companycode    A     B     C       ...
1234           Jid   4123  141
6472           Low   1312  3234
...

同一个公司代码的名称和地址始终相同

我想以最终看起来像这样的方式连接、加入、合并或追加它们:

companycode    name    address    A     B     C     ...
1234           asd     qwe,56     Tyh   123   923
1234           asd     qwe,56     Zfhs  4828  01992
6472           yui     iop,56     Retgh 8484  8484
1234           asd     qwe,56     Jid   4123  141
6472           yui     iop,56     Low   1312  3234
...

由于单个公司代码的名称和地址始终相同,基本上我想在 axis=0 中连接 df2 和 df,并将原始 df 公司代码中的名称和地址拉到这个新行。写起来很混乱,但我认为视觉效果更好。

知道我该怎么做吗?

pd.concat 后跟 groupby 操作应该可以做到。

df = pd.concat([df1, df2], 0, ignore_index=True)\
                          .groupby('companycode').ffill()
df

       A     B     C address  companycode name
0    Tyh   123   923  qwe,56         1234  asd
1   Zfhs  4828  1992  qwe,56         1234  asd
2  Retgh  8484  8484  iop,56         6472  yui
3    Jid  4123   141  qwe,56         1234  asd
4    Low  1312  3234  iop,56         6472  yui

  • ignore_index=True 设置为在连接时创建新索引
  • 串联在 df2 的列中留下 NaN 值,这些值以前不存在
  • companycode 执行 groupby 操作,然后对 ffill 执行操作,以使用同一组中的正确值填充那些 NaN

对于那些有 SQL 心态的人,考虑 mergeconcat(即 JOINUNION):

mdf = df1[['companycode', 'name', 'address']]\ 
              .merge(df2, on='companycode').drop_duplicates()
finaldf = pd.concat([df1, mdf]).reset_index(drop=True)

print(finaldf)
#    companycode name address      A     B     C
# 0         1234  asd  qwe,56    Tyh   123   923
# 1         1234  asd  qwe,56   Zfhs  4828  1992
# 2         6472  yui  iop,56  Retgh  8484  8484
# 3         1234  asd  qwe,56    Jid  4123   141
# 4         6472  yui  iop,56    Low  1312  3234