How to write an data array to excel in a row instead of in a column using pandas in Python

ε祈祈猫儿з 提交于 2021-02-10 16:02:21

问题


a= [1,2,3,4,5]
df=DataFrame(a)

.... #setup excelwriter and dataframe

df.to_excel(writer, sheet_name=sheetname,startrow=1, startcol=1, header=False, index=False)

Output:

1\n
2\n
3\n
4\n
5

How can I get output as:

1    2    3    4    5

回答1:


To output in a line use this:

df = df.transpose()

Full code:

#!/usr/bin/python
import pandas as pd 
import xlsxwriter as xlsw

a = [1,2,3,4,5]
df = pd.DataFrame(a)
df = df.transpose()
xlsfile = 'pandas_simple.xlsx'
writer = pd.ExcelWriter(xlsfile, engine='xlsxwriter')

df.to_excel(writer, sheet_name="Sheet1Name",startrow=1, startcol=1, header=False, index=False)

https://github.com/tigertv/stackoverflow-answers




回答2:


You could transpose first, and then save to excel:

df

   0
0  1
1  2
2  3
3  4
4  5

df.T.to_excel(writer, 
              sheet_name=sheetname,
              startrow=1, 
              startcol=1, 
              header=False, 
              index=False)

1   2   3   4   5



回答3:


Use transpose() on dataframe to convert columns into rows.

import pandas as pd

a= [1,2,3,4,5]
df=pd.DataFrame(a)
df = df.transpose()

print(df)

result:

   0  1  2  3  4
0  1  2  3  4  5


来源:https://stackoverflow.com/questions/48613158/how-to-write-an-data-array-to-excel-in-a-row-instead-of-in-a-column-using-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!