在数据框的第N列后插入空格或空白列

2024-04-24 23:04:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有3个数据帧,我把它们连接成一个数据帧。但是,现在我需要在每第二列之后插入一个空白列(correlation) 然后将其写入excel。所以每个数据帧看起来像:

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 

在它们串联之后,再加上空格或空白列,它们的格式应该是:

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

有人能帮我吗?你知道吗


Tags: 数据namestatusdaysvariable空白activedisconnect
2条回答

使用range每2列一个startcol参数一个,如下所示:

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()

如果有单独的数据帧,则:

for df,st_col  in zip([df1,df2,df3], range(0,7,3)):
    df.to_excel(writer, index=False, startcol=st_col)

将在excel中另存为: output

尝试使用“insert”方法。像这样:

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)

相关问题 更多 >