'How do i loop through columns in a dataframe when using win32com in Python?

I am writing code to send a batch of reminders in outlook using win32com and i have created a dataframe including the date and corresponding subject of each reminder. The dataframe named 'data' looks as below (there are much more rows in actuality):

date subject
01/04/2022 13:00:00 emails
04/04/2022 15:00:00 meeting
08/04/2022 15:00:00 meeting

The following code is what i have come up with at the moment but im running into a 'TypeError: string indices must be integers' error which i cant seem to get my head around.

def sendreminder(df)
    for i in df[['date','subject']]:
        appt = outlook.CreateItem(1)
        appt.Start = df['date'[i]]
        appt.Subject = df['subject'[i]]
        appt.Duration = 1
        appt.Recipients.Add('[email protected]')
        appt.Save()
        appt.Display(True)
        appt.Send()
sendmeeting(data)

What i would like the code to do is to loop through the dataframe and create a reminder for each date with its corresponding subject header.

Any help would be greatly appreciated.



Solution 1:[1]

First, usually looping over dataframe rows is not the way to go with pandas because it is slower than using vectorized operations.

There is also a problem with your loop:

> import pandas as pd
> from datetime import datetime
>df = pd.DataFrame({
        'date': [
                datetime.strptime('01/04/2022 13:00:00', '%d/%m/%Y %H:%M:%S'),
                datetime.strptime('04/04/2022 15:00:00', '%d/%m/%Y %H:%M:%S'),
                datetime.strptime('08/04/2022 15:00:00', '%d/%m/%Y %H:%M:%S')
        ],
        'subject': ['emails', 'meeting', 'meeting']
})
> print(df)

| | date | subject |
| - | - | - |
|0 | 2022-04-01 13:00:00 | emails |
|1 | 2022-04-04 15:00:00 | meeting |
|2 | 2022-04-08 15:00:00 | meeting |
> for i in df[['date', 'subject']]:
    print(i)

date
subject

If you want to loop over rows of the dataframe, you can use itertuples:

> def sendreminder(df):
    for r in df.itertuples(index=False):
        # appt = outlook.CreateItem(1)
        start = r.date
        subject = r.subject
        print(f'appt.Start : {start}')
        print(f'appt.Subject : {subject}\n')

> sendreminder(df)

appt.Start : 2022-04-01 13:00:00
appt.Subject : emails

appt.Start : 2022-04-04 15:00:00
appt.Subject : meeting

appt.Start : 2022-04-08 15:00:00
appt.Subject : meeting

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ibmx