0
$\begingroup$
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.

$\endgroup$

1 Answer 1

0
$\begingroup$

Assuming that each invoice id has only 1 unique customer id something like this should work:

df["CustomerID"] = df.groupby("InvoiceNo")["Customer ID"].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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.