How can I replace NaN values with other values in the CustomerID column if they have a same InvoiceNo? InvoiceNo
StockCode
Quantity
InvoiceDate
UnitPrice
CustomerID
Country




573415
23434
20
2011-10-30 16:17:00
0.79
13607.0
UK


:--------
:---------
:---------
:-------------------
:---------
:----------
:-------


539050
22480
2
2010-12-15 16:21:00
1.25
12577.0
France


:--------
:---------
:---------
:-------------------
:---------
:----------
:-------


573415
23434
1
2011-01-13 14:29:00
4.13
NaN
UK


:--------
:---------
:---------
:-------------------
:---------
:----------
:-------


573151
84692
25
2011-10-27 20:09:00
0.42
17602.0
UK


:--------
:---------
:---------
:-------------------
:---------
:----------
:-------


539050
22480
4
2011-12-02 16:39:00
10.79
NaN
UK


:--------
:---------
:---------
:-------------------
:---------
:----------
:-------




Here I would like to replace the NaN values in the CustomerID with the values in CustomerID column if the InvoiceNo values are same.
Assuming that each invoice id has only 1 unique customer id something like this should work:
df[&quot;CustomerID&quot;] = df.groupby(&quot;InvoiceNo&quot;)[&quot;Customer ID&quot;].apply(lambda x: x.ffill().bfill())

The code above simply makes groups based on the customer id and forward an backward fills all NA values.