I am starting with a pandas Dataframe that is generated by the following code:
import pandas as pd
data = {'basket_1':['apple;banana;orange', 'apple;banana;mango', 'mango;orange;grapefruit'],
'basket_2':['pineapple;strawberry;peach', 'peach;lemon;guava', 'strawberry;peach;guava']}
# Create DataFrame
df = pd.DataFrame(data)
basket_1 basket_2
0 apple;banana;orange pineapple;strawberry;peach
1 apple;banana;mango peach;lemon;guava
2 mango;orange;grapefruit strawberry;peach;guava
I also start with a numpy array of all of the fruits present in either basket column (as well as some additional fruits), generated as follows for the purpose of this example:
import numpy as np
fruits = np.array(['apple', 'banana', 'orange', 'mango', 'grapefruit', 'kiwi', 'pineapple',
'strawberry', 'peach', 'lemon', 'guava', 'lime'])
From this initial Dataframe and array, I am looking to generate the resulting Dataframe in the most efficient way possible:
basket_1 basket_2 apple banana orange mango grapefruit kiwi pineapple strawberry peach lemon guava lime
0 apple;banana;orange pineapple;strawberry;peach 1 1 1 0 0 0 2 2 2 0 0 0
1 apple;banana;mango peach;lemon;guava 1 1 0 1 0 0 0 0 2 2 2 0
2 mango;orange;grapefruit strawberry;peach;guava 0 0 1 1 1 0 0 2 2 0 2 0
The final result has added a column for each of the elements present in the fruits array along with a '1' in a given row if the given fruit is present in the 'basket_1' column, a '2' in a given row if the given fruit is present in the 'basket_2' column, and a '0' otherwise.
At the moment, I am using the following code to transform the initial Dataframe into the desired format:
def whichBasket(b1, b2, fruit):
if fruit in b1:
val = 1
elif fruit in b2:
val = 2
else:
val = 0
return val
for f in fruits:
df[f] = df.apply(lambda x: whichBasket(x.basket_1, x.basket_2, f), 1)
This solution calls an apply function iterating through each row of the Dataframe nested inside a for-loop iterating through each fruit, which works fine for a small example such as this one. However, I am attempting to scale this up to a Dataframe with over 1000 fruits and over 80000 rows, and this solution is far too slow to complete this job in a reasonable amount of time.
Any ideas for ways to improve this code's performance in terms of shortening running time? Thanks in advance for your help.