You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python openpyxl将Pandas一维DataFrame横向写入Excel?能否配置写入方向?

How to Write a 1D Pandas DataFrame Horizontally to Excel

Great question! Unfortunately, pandas' to_excel method doesn’t have a built-in parameter to control writing direction (vertical vs horizontal) directly. But the fix is simple—you just need to transpose your DataFrame before writing it to Excel.

Why This Works

Your 1D DataFrame is structured as a single column of values. Transposing it converts that column into a single row, which will then be written horizontally across columns instead of vertically down rows.

Modified Code

Here’s how to adjust your existing code to get the horizontal output you want:

writer = pd.ExcelWriter(fn, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

# Transpose the DataFrame before writing to switch to horizontal direction
df_2.T.to_excel(writer, sheet_name='Sheet3', header=None, index=False, startcol=1, startrow=1)

writer.save()

Note for Series Data

If your df_2 is actually a pandas Series (instead of a single-column DataFrame), you’ll need to convert it to a DataFrame first before transposing:

df_2.to_frame().T.to_excel(writer, sheet_name='Sheet3', header=None, index=False, startcol=1, startrow=1)

What This Does

With this change, your values [10, 9, 8, 7, 6] will be written starting at cell B2 (since startcol=1 and startrow=1 are 0-indexed) and spread horizontally across B2 → C2 → D2 → E2 → F2, instead of stacking vertically down B2 → B3 → B4 → B5 → B6.

This approach keeps using the startrow and startcol parameters you’re already comfortable with, so you can control the starting position exactly as before.

内容的提问来源于stack exchange,提问作者Jacky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:41:21