Merv Merzoug
Merv Merzoug

Reputation: 1237

Loop through rows of pandas dataframe and create variables based on columns

I have a pandas.DataFrame with df.columns = ['jobID', 'emailAddress', 'jobTitle', 'jobSource', 'contactName'] and index_col = 'jobID'

My objective is to loop through each row of this dataframe and create variables based on the value of each 'cell' (intersection of column and row) and pass that to a function I wrote that automates email generation and sending.

This is what I have so far, but this doesn't get it done.

for row in df.index():
    email = str(df['emailAddress'])
    jobTitle = str(df['jobTitle'])
    jobSource = str(df['jobSource'])
    jobID = str(df['jobID'])
    nameOfContact = str(df['contactName'])

    """ generate the email subject using string methods
    'This is a subject about %s' % (jobTitle)
    """
    subj = emailSubj(jobSource = jobSource,
              jobTitle = jobTitle,
              jobID = jobID)

    """
    create email body using similar logic as subject
    """
    body = create_emailBody(nameOfContact = nameOfContact)
    """
    Generate and send the email by passing email address, subject, body
    """
    emailTool(email = email,
              subj = subj,
              body = body)

This script does run, but I don't think I am properly looping through the rows and naming the variables. I am receiving the entire column instead of the cell.

Upvotes: 0

Views: 1195

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210842

you can use .apply(..., axis=1):

df.apply(lambda r: 
            emailTool(email=r['emailAddress'],
                      subj=emailSubj(jobSource=r['jobSource'],
                                     jobTitle=r['jobTitle'],
                                     jobID=r['jobID']),
                      body=create_emailBody(nameOfContact=r['contactName'])
            ),
         axis=1
)

Upvotes: 1

Related Questions