Home > OS >  for loop through multiple items based on a dataframe
for loop through multiple items based on a dataframe

Time:01-27

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

CodePudding user response:

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:

enter image description here

CodePudding user response:

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

write_to_sheet(table1)
write_to_sheet(table2)

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

  • Related