0

Following up on my previous question

I have a list of records as shown below taken from this table

itemImage name nameFontSize nameW nameH conutry countryFont countryW countryH code codeFontSize codeW codeH
sample.jpg Apple 142 1200 200 US 132 1200 400 1564 82 1300 600
sample2.jpg Orange 142 1200 200 UK 132 1200 400 1562 82 1300 600
sample3.jpg Lemon 142 1200 200 FR 132 1200 400 1563 82 1300 600

Right now, I have one function setText which takes all the elements of a row from this table. I only have name, country and code for now but will be adding other stuff in the future.

I want to make this code more future proof and dynamic. For example, If I added four new columns in my data following the same pattern. How do I make python automatically adjust to that? instead of me going and declaring variables in my code every time.

Basically, I want to send each 4 columns starting from name to a function then continue till no column is left. Once that's done go to the next row and continue the loop.

Thanks to @Samwise who helped me clean up the code a bit.

import os
from PIL import Image,ImageFont,ImageDraw, features
import pandas as pd

path='./'
files = []
for (dirpath, dirnames, filenames) in os.walk(path):
    files.extend(filenames)

df = pd.read_excel (r'./data.xlsx')
records = list(df.to_records(index=False))

def setText(itemImage, name, nameFontSize, nameW, nameH,
            conutry, countryFontSize,countryW, countryH,
            code, codeFontSize, codeW, codeH):
    font1 = ImageFont.truetype(r'./font.ttf', nameFontSize)
    font2 = ImageFont.truetype(r'./font.ttf', countryFontSize)
    font3 = ImageFont.truetype(r'./font.ttf', codeFontSize)

    file = Image.open(f"./{itemImage}")
    draw = ImageDraw.Draw(file)

    draw.text((nameW, nameH), name, font=font1, fill='#ff0000',
    align="right",anchor="rm")
    draw.text((countryW, countryH), conutry, font=font2, fill='#ff0000',
    align="right",anchor="rm")
    draw.text((codeW, codeH), str(code), font=font3, fill='#ff0000',
    align="right",anchor="rm")

    file.save(f'done {itemImage}')

for i in records:
    setText(*i)

1 Answers1

0

Sounds like df.columns might help. It returns a list, then you can iterate through whatever cols are present.

for col in df.columns():

The answers in this thread should help dial you in:

How to iterate over columns of pandas dataframe to run regression

It sounds like you also want row-wise results, so you could nest within df.iterrows or vice versa...though going cell by cell is generally not desirable and could end up being quite slow as your df grows.

So perhaps be thinking about how you could use your function with df.apply()

CreekGeek
  • 1,809
  • 2
  • 14
  • 24