So I have several dataframes of different widths.
I want a for loop that will perform an operation on each dataframe's columns:
Table 1:
col1 | col2 | col3 |
---|---|---|
Hi | 1 | Jake |
Bye | 2 | Mike |
Red | Blue | Pink |
Table 2:
cl1 | cl2 | cl3 | c4 |
---|---|---|---|
Frank | Toy | Hello | Present |
Bike | Ride | Blue | Mike |
Red | Blue | Pink | Fred |
These tables are in the form a list of tuples.
I want to take these two loops an effectively just have one loop that takes the number of header as the number of items to loop through.
row = 1
col = 0
for col1, col2, col3 in (table):
worksheet.write(row, col, col1)
worksheet.write(row, col + 1, col2)
worksheet.write(row, col + 2, col3)
row += 1
row = 1
col = 0
for cl1, cl2, cl3, cl4 in (table):
worksheet.write(row, col, cl1)
worksheet.write(row, col + 1, cl2)
worksheet.write(row, col + 2, cl3)
worksheet.write(row, col + 2, cl3)
row += 1
Here's what I want
iterate through each column in the table no matter the number of columns. What I think it would look like
row = 1
col = 0
elements = table.column.names
for elements in (table):
for i in elements:
worksheet.write(row, col, i)
col = col +1
row = row +1
It looks to me that you are looking for something like this:
import pandas as pd
import xlsxwriter
book = xlsxwriter.Workbook('example.xlsx')
worksheet = book.add_worksheet("sheet1")
shape = df2.shape
for col in range(shape[1]):
for row in range(shape[0]):
worksheet.write(row, col, df2.iloc[row, col])
book.close()
what generate: