如何在Python

时间:2018-02-04 21:25:28

标签: python arrays excel pandas

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

.... #setup excelwriter和dataframe

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

输出:

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

如何获得输出:

1    2    3    4    5

3 个答案:

答案 0 :(得分:2)

您可以先转置,然后保存到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

答案 1 :(得分:1)

在数据框上使用transpose()将列转换为行。

import pandas as pd

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

print(df)

结果:

   0  1  2  3  4
0  1  2  3  4  5

答案 2 :(得分:1)

要在一行中输出,请使用:

df = df.transpose()

完整代码:

#!/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