Writing to an Excel spreadsheet

后端 未结 12 2006
不知归路
不知归路 2020-11-22 04:39

I am new to Python. I need to write some data from my program to a spreadsheet. I\'ve searched online and there seem to be many packages available (xlwt, XlsXcessive, openpy

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 05:06

    Use DataFrame.to_excel from pandas. Pandas allows you to represent your data in functionally rich datastructures and will let you read in excel files as well.

    You will first have to convert your data into a DataFrame and then save it into an excel file like so:

    In [1]: from pandas import DataFrame
    In [2]: l1 = [1,2,3,4]
    In [3]: l2 = [1,2,3,4]
    In [3]: df = DataFrame({'Stimulus Time': l1, 'Reaction Time': l2})
    In [4]: df
    Out[4]: 
       Reaction Time  Stimulus Time
    0              1              1
    1              2              2
    2              3              3
    3              4              4
    
    In [5]: df.to_excel('test.xlsx', sheet_name='sheet1', index=False)
    

    and the excel file that comes out looks like this:

    enter image description here

    Note that both lists need to be of equal length else pandas will complain. To solve this, replace all missing values with None.

提交回复
热议问题