for loop through multiple items based on a dataframe


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
Asked By: David 54321



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])

what generate:

enter image description here

Answered By: jjsantoso

Firstly, you DON’T have any dataframes in your code. In python DataFrames are a specific container type provided in the pandas module. And while you don’t have any here, you probably should as they are more useful than lists of tuples. Secondly, if I understand you correctly, you want the ability to loop through any table you provide and perform the same actions. This is what functions/methods are for. Declare a function that you then call with each table as a parameter. Assuming your tables are dataframes:

def write_to_sheet(table):
    for row in table.index:
        for column in table:
            r = list(tables.index).index(row)
            c = list(tables.columns).index(column)
            worksheet.write(r, c, table.loc[row][column])


You will of course need to import your data into pandas dataframes but that is a subject for another question (which you will of course research before asking here as it has been asked many times before).

Answered By: Galo do Leste
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.