Save data in. xlsx format with pandas

Asked

Viewed 3,961 times

0

Good afternoon! I want to save in a file . xlsx the loop number that my code is running, but the way it is, saves only the last loop.

import time
import pandas as pd

loop = 0

print('Loop')

writer = pd.ExcelWriter('/home/pi/Área de Trabalho/saidaCamera3.xlsx')


while True:
        loop = loop + 1

        df = pd.DataFrame({'Loop': [loop]})
        df.to_excel(writer, 'Camera RGB', index=False)
        writer.save()
        if loop>=32:
            break

writer.save()

It seems a bit silly, but then I’ll join with my sensor reading.

1 answer

1

The problem is that with every passage in the loop, you are creating a DataFrame new. Change your code to the following:

import time
import pandas as pd

loop = 0

df = pd.DataFrame()

while True:
    loop = loop + 1
    print('Loop: ', loop)
    df = df.append({'Loop': [loop]}, ignore_index=True)

    if loop >= 32:
        break

print(df.shape)

df.to_excel('/home/pi/Área de Trabalho/saidaCamera3.xlsx', index = False)

Note that the initialization of DataFrame is out of the loop, and that with each passage through this, a new line is added. At the end of the loop, DataFrame is persisted in Excel file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.