将系列中的值映射到列上以替换 nan 值 pandas

Mapping values from series over a column to replace nan values pandas

我有一个 DataFrame,其中包含作业编号和与该作业关联的客户名称。在某些情况下,作业编号没有客户名称,因此为空。 我有一个单独的系列,其中有这些工作编号作为索引和缺失的客户名称以根据工作编号替换空值。我不完全确定如何将其映射到原始 DataFrame 列。

这是原始DataFrame (df):

   Job Number  Customer 
0    02123      Paul F
1    46456      nan
2    56823      Kevin T
3    62948      nan

要替换 nan 值的系列:

Job Number
  46456     Kara L
  62948     Sabrina M
  Name: Customers, dtype: object

我需要的最终输出是:

   Job Number  Customer 
0    02123      Paul F
1    46456      Kara L
2    56823      Kevin T
3    62948      Sabrina M

我希望这是有道理的。我查看了其他答案,例如使用:df['Customer'] = df['Job Number'].map(customers) 但这没有用或 test['Customer'] = df['Customer'].combine_first(df['Customer'].map(customers)).

我不确定如何将代码粘贴到这里,所以我手写了 df 和系列。

如有任何帮助,我们将不胜感激。

您可以将 reset_indexcombine_first 一起使用:

(df.set_index('JobNumber').squeeze()
   .combine_first(customers.set_index('Job').squeeze())
   .reset_index())

       index  Customer
    0   2123     Paul F
    1  46456     Kara L
    2  56823    Kevin T
    3  62948  Sabrina M

这里有必要使用 map by column Job Number 而不是 Customer:

df['Customer'] = df['Customer'].combine_first(df['Job Number'].map(customers))
print (df)
   Job Number   Customer
0        2123     Paul F
1       46456     Kara L
2       56823    Kevin T
3       62948  Sabrina M

详情:

print (df['Job Number'].map(customers))
0          NaN
1       Kara L
2          NaN
3    Sabrina M
Name: Job Number, dtype: object