I have written a function (incorporating bits and pieces scavenged from stack overflow) that will move throughout a data frame by row, interleaving strings from col-x to col-y, for all two column x,y pair in all rows.
I have a working solution. The problem is that it is slow going on large data frames.
Is there a quicker way?
I have tried the following setup:
# Import modules
import pandas as pd
from itertools import chain, zip_longest
def interleave_strings(string1, string2):
tuples = zip_longest(string1, string2, fillvalue='')
string_list = [''.join(item) for item in tuples]
return ''.join(string_list)
# Create the pandas DataFrame
data = [['timy', 'toma', 'tama', 'tima', 'tomy', 'tome'], ['nicka', 'nacka', 'nucka', 'necka', 'nomy', 'nome'], ['julia', 'Julia', 'jalia', 'jilia', 'jomy', 'jome']]
df = pd.DataFrame(data, columns = ['A', 'B', 'C', 'D', 'E', 'F'])
df
This gets us...
timy toma tama tima tomy tome
nicka nacka nucka necka nomy nome
julia Julia jalia jilia jomy jome
And this works, but slowly...
# new_df
il_df = pd.DataFrame()
for i in range (int(len(df.columns)/2)):
selection = df.iloc[:,2*i:2*i+2]
L = []
for j in range (len(df.index)):
res = interleave_strings(selection.iloc[j,0], selection.iloc[j,1])
L.append(res)
S = pd.Series(L)
#il_df = pd.concat(D, ignore_index=True)
il_df = il_df.append(S, ignore_index=True)
And with
il_df.transpose()
The correct output is:
0 1 2
0 ttiommya ttaimmaa ttoommye
1 nniacckkaa nnuecckkaa nnoommye
2 jJuulliiaa jjailliiaa jjoommye