【问题标题】:How to splice a dataframe into smaller tables and save each table to an excel sheet如何将数据框拼接成较小的表格并将每个表格保存到 Excel 工作表中
【发布时间】:2022-01-17 03:23:29
【问题描述】:

这是一张桌子

df = {'index':['Larry','Moe','Curly'],
  'age':[54,58,65],
  'eye':['blue','brown','brown'],
  'fortune':[1,1.5,1.2],
  'food':['pizza','pasta','burgers'],
  'job':['actor','actor','actor'],
  'kids':[2,3,4]}

df = pd.DataFrame(df)
df = df.set_index('index')

我想从这个表中创建 3 个迷你表,并将每个迷你表保存为 1 个 Excel 文件中的工作表。第一个阶段应该包含列年龄和眼睛,第二个,财富和食物,第三个,工作和孩子。

这是我尝试过的,但没有多大意义

col = df.columns
with pd.Excelwriter('filename' + '.xlsx') as xlswriter:
     for col in df:
        col = col[::2]
df.to_excel(xlswriter, index=False, sheet_name = 'sheet' )

【问题讨论】:

    标签: python pandas dataframe loops


    【解决方案1】:

    如果您希望将每两列保存到单独的工作表中,请尝试:

    col = df.columns
    
    # ExcelWriter not Excelwriter
    with pd.ExcelWriter('filename' + '.xlsx') as xlswriter:
         for i in range(0,len(col), 2):
            # you can use `iloc` to slice by column number
            df.iloc[:,i:i+2].to_excel(xlswriter, index=False,      # are you sure you want to remove the index?
                                      sheet_name = f'sheet {i}' )  # change sheet name so you don't override your data
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多