Reputation: 1048
I have 3 dataframes and I have concatenated them into a single dataframe. However,now I need to insert a blank column after every 2nd column(correlation) in this dataframe and then write it to excel. So each one dataframe looks like:
Variable_Name correlation
Pending_Disconnect 0.553395448
status_Active 0.539464806
days_active 0.414774231
days_pend_disco 0.392915837
prop_tenure 0.074321692
abs_change_3m 0.062267386
And after their concatenation and then space or blank column append they should be of the format:
Variable_Name correlation Variable_Name correlation Variable_Name correlation
Pending_Disconnect 0.553395448 Pending_Change 0.043461995 active_frq_N 0.025697016
status_Active 0.539464806 status_Active 0.038057697 active_frq_Y 0.025697016
days_active 0.414774231 ethnic 0.037503202 ethnic 0.025195149
days_pend_disco 0.392915837 days_active 0.037227245 ecgroup 0.023192408
prop_tenure 0.074321692 archetype_grp 0.035761434 age 0.023121305
abs_change_3m 0.062267386 age_nan 0.035761434 archetype_nan 0.023121305
Can someone please help me with this?
Upvotes: 1
Views: 873
Reputation: 13255
Use range
one for every 2 columns and one for startcol
parameter as:
import xlsxwriter
writer = pd.ExcelWriter('pandas_column_formats.xlsx',engine='xlsxwriter')
for col,st_col in zip(range(0,6,2), range(0,7,3)):
df.iloc[:,col:col+2].to_excel(writer, index=False, startcol=st_col)
writer.save()
writer.close()
If you have data frames separately then:
for df,st_col in zip([df1,df2,df3], range(0,7,3)):
df.to_excel(writer, index=False, startcol=st_col)
Upvotes: 3
Reputation: 1527
Try using the method 'insert'. Something like this:
N = len(df.columns) - 2 # number of columns, starting 2 before the last one
for i in range(N,2,-2): # going backwards since the column numbers change during insertion
df.insert(i,'','',allow_duplicates=True)
Upvotes: 1