Home > Net >  how to filter a DF groupby object to a list
how to filter a DF groupby object to a list

Time:12-05

I am filtering a dataframe and sending the results of the info in an email using smtplib. Here's what I got so far.

def SMTP_Emailer(content, receiver):
    msg = EmailMessage()
    msg['Subject'] = "Test Email!"
    msg['From'] = '[email protected]'
    msg['To'] = [receiver]

    msg.set_content( f""" This is a test email, please disregard{content}
        """,  subtype='html')


    with smtplib.SMTP('sendsmtp.server.com', 1234) as s:
                s.send_message(msg)

I have a pandas dataframe like this:

d = 
  STATE   CUSTOMER      ORDERS     EMAIL OWNER
0    ID   Jerry         10        [email protected]  
1    MT   Tom           119       [email protected]
2    CA   Patrick       87        [email protected]
3    WA    Lucy         918       [email protected]

Then Im grouping by the series d['EMAIL OWNER']

grouped = df.groupby("EMAIL TEST")
    for emails, data  in grouped:
        print(emails)
        dataframes = [emails for e, group in grouped]
        print(dataframes)
        SMTP_Emailer(data.loc[:, :].to_html(), dataframes)

Im expecting ['[email protected] ', '[email protected] '] so that I can put them in my msg['To']

but I'm unexpectedly getting ['[email protected] ','[email protected] '] in VS Code

and in jupyter notebook I'm getting:

[email protected]
['[email protected]', '[email protected]']
[email protected]
['[email protected]', '[email protected]']

Result outcome is 2 separate emails to occur. I used the groupby to filter from the main data source(d) by the persons email address so that they'd only see what was owned by them and not the other person. So Mark wouldnt see Jerry's data (and the other way around)

Let me know if this helps clarify things.

#Email 1  gets sent to [email protected]

Email 1 = 
 
  STATE   CUSTOMER      ORDERS     EMAIL OWNER
0    ID   Jerry         10        [email protected]  
1    MT   Tom           119       [email protected]
2    CA   Patrick       87        [email protected]

#Email 2  gets sent to [email protected]

Email 2 =

3   WA    Lucy         918       [email protected]

CodePudding user response:

Glad you solved your problem! I just wanted to show how you could have used groupby if you were still interested. In your answer you pretty much made a groupby (!):

for email,dfuser in df.groupby('EMAIL OWNER'):
    SMTP_Emailer(dfuser.to_html(), email)

CodePudding user response:

So the groupby was a mistake. It was a lot easier to write the code like this and then filter the data frame for the user that I wanted. I realized I was making copies of the dataframe that already existed. Here's the final code:

    for email in df['EMAIL OWNER'].unique().tolist():
        dfuser = df.loc[df[' EMAIL OWNER'] == email]

        SMTP_Emailer(dfuser.to_html(), email)
  • Related