I am concatenating columns of a Python Pandas Dataframe and want to improve the speed of my code.
My data has the following structure:
Apple Pear Cherry
1 2 3
4 5 NaN
7 8 9
I only want to concatenate the contents of the Cherry column if there is actually value in the respective row. If my code works correctly, the result of the example above should be:
Result
1 :: 2 :: 3
4 :: 5
7 :: 8 :: 9
My code so far is this:
a_dataframe[result] = a_dataframe.apply(lambda r:
str(r.loc['apple']) + ' :: ' + str(r.loc['pear'])+' :: '+str(r.loc['cherry'])
if pd.notnull(r.loc['cherry']) & (r.loc['cherry'] != "")
# if cherry value is empty, do not add cherry into result
else str(r.loc['apple']) + ' :: ' + str(r.loc['pear']),
axis=1)
Any thoughts on how I can improve the speed of my code? Can I run this without an apply statement using only Pandas column operations?
Thanks up front for the help.