I currently have 2 dataframes, A and B. These dataframes are generated in runtime, and increase in size according to parameters in the program execution.
I need to evaluate how many times a value in dataframe A is lesser than all the values in dataframe B.
For example:
Dataframe A
+-----+-------+
| id | value |
+-----+-------+
| 1 | 0.23 |
| 2 | 1.2 |
+-----+-------+
Dataframe B
+-----+-------+
| id | value |
+-----+-------+
| 1 | 0.22 |
| 2 | 1.25 |
| 3 | 0.3 |
| 4 | 0.5 |
| 5 | 0.9 |
| 6 | 0.0 |
+-----+-------+
I need to check how many values greater than 0.23 (for example) are in dataframe B. in this case 4 of the 6.
My first try with this was using this code. In this case, bio_dataframe
is dataframe A, an random_seq_df
is dataframe B.
for bio_row in bio_dataframe.itertuples():
total = 0
for ran_row in random_seq_df.itertuples():
if bio_row[2] < ran_row[2]:
total += 1
As you can see, i use itertuples
for fast iteration of the rows of the dataframes.
This approach works "well" for dataframes below 25000 rows, but beyond that it starts to get painfully slow.
So my next approach was this.
final_res
is a column in the dataframe.
for bio_row in bio_dataframe.itertuples():
a = bio_row[2]
total = random_dataframe.eval('final_res > @a')
It works excellent until 100000 rows, beyond that the story repeats.
I'm hitting a wall here and I've run out of ideas to test. Is there any way to improve the code? Am I missing something, or some snippet to make it faster?
(bio_dataframe < random_dataframe.min()).sum()
? Also, the Indentation in your first code block is off. \$\endgroup\$