Skip to content
Advertisement

Extracting Rows and Appending Them to the End of Other Rows

I have a dataframe containing a transaction list. What I want to do is create something like a P&L per transaction and additionally make it suitable for entry into another software.

Basically, I would like to get a “Buy” transaction and find the next row with a “Sell” transaction. Then take that “Sell” transaction and append it to the end of the “Buy” row. Alternatively, it can be short action: in such case, I’d be taking the “Sell” transaction, search for the next (closest in time) “Buy” transaction, and add it to the end of the “Buy” row.

Input dataframe:

JavaScript

Desired outcome:

JavaScript

The only idea that comes to mind is to loop through all rows and individually append them to the end of others but it is hardly an efficient way. Can someone recommend me a Pythonic way of achieving the desired outcome?

Advertisement

Answer

You can use:

JavaScript

Output:

JavaScript

First, we count the occurrence of each side. The first occurrence of “Sell” has index index 0, the second one has index 1 and so on. It’s the same for “Buy” because we use groupby on Side column.

JavaScript

Now we have the row index of your new dataframe but we have to align each index of one side to other side (0 -> 0, 1 -> 1, …). As you have 2 sides, we can use duplicated because the first occurrence of 0 is False and the second occurrence of 0 is True. It acts as a boolean mask:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement