簡體   English   中英

在數據幀的第N列之后插入空格或空白列

[英]Inserting space or blank column after N'th column in a dataframe

我有3個數據框,並且已將它們串聯為一個數據框。 但是,現在我需要在此數據框中的每個第二列(相關性)之后插入一個空白列,然后將其寫入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

有人可以幫我嗎?

每2列使用range一,對於startcol參數使用range為:

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中保存為: 產量

嘗試使用“插入”方法。 像這樣:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM