Search code examples
pythonpython-3.xpandasdataframepyexcelerate

Dataframe print index using pyexcelerate


How do I get to display index on my output excel sheet? Here is my code:

data = [df.columns.tolist(), ] + df.values.tolist()
wb = Workbook()
wb.new_sheet("sample", data=data)
wb.save("output.xlsx")

How do I show index as the first column? I was able to do that using openpyxl and setting index = True.

Edit1: Updated code using the code below:

data = [myNewDF.columns.tolist()] + myNewDF.values.tolist()
data = [[index] + row for index, row in zip(myNewDF.index, data)]

This almost works except 1 row goes missing.Results displaying is below:

TestA   A   B   C   D   E 
TestB   1   1   1   1   0 
TestC   0   0   0   1   1 
TestD   0   1   1   0   1

the ideal results should be:

        A   B   C   D   E 
TestA   1   1   1   1   0 
TestB   0   0   0   1   1 
TestC   0   1   1   0   1
TestD   1   0   0   0   0

Input file:

ColumnA ColumnB
TestA   A
TestA   B
TestA   C
TestA   D
TestB   D
TestB   E
TestC   C
TestC   B
TestC   E
TestD   A

Edit2:Actual working modified code:

data = [myNewDF.columns.tolist()] + myNewDF.values.tolist()
ind =[""] + myNewDF.index.tolist())
data = [[index] + row for index, row in zip(ind, data)]

Solution

  • Maybe just include the index in the data?

    df = DataFrame({'Name': ['a', 'b', 'c'], 'Age': ['one', 'two', 'three']})
    data = [df.columns.tolist()] + df.values.tolist()
    data = [[index] + row for index, row in zip(df.index, data)]