Я не понимаю, почему я получаю ошибку "слишком много значений для распаковки" - PullRequest
0 голосов
/ 07 января 2020

Когда я запускаю это, я могу заставить его спросить у меня пароль, но когда он запускает мой "для" l oop, я получаю ошибку, обновляя мои данные.

import csv, smtplib, ssl
import pandas as pd 


newhire = pd.read_csv('New_Hires_Test.csv', delimiter = ",", skiprows=7)   #Open up the document and 
skip header

newhire["Email"] = "test@gmail.com"     #Add a row 'Email' and add email address

mask = newhire["New IT Item"] == "New"      #brings back only new in "New IT Item column"

message = """\Subject: {Effective Date}
From: test@gmail.com
To: test@gmail.com 

Hello IT, 

We have a new user by the name of {StartDate}. The new user will be starting on {Employee} and will 
be working at {PC}. 
Their title will be {Title} and their supervisor is {Supervisor}"""

from_address = "test@gmail.com"
password = input("Type your password and press enter: ")


context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
    server.login(from_address, password)

    for Employee, StartDate, PC, Title, Supervisor, Email in newhire[mask]:
        server.sendmail(
            from_address,
            Email,
            message.format(Employee=Employee, StartDate=StartDate, PC=PC, Title=Title, Email=Email, 
Supervisor=Supervisor)
        )

print('Emails were sent successfully!')

***ValueError: too many values to unpack (expected 6)***

Я глядя на мое "для" l oop, и я вижу, что есть 6 столбцов, которые я ищу. Все мои данные являются строками, и я установил разделитель, чтобы убедиться, что все данные разделены правильно. Я думаю, что я просто пропускаю проблему или не понимаю мои данные.

****New_Hires_Test.csv***
Report:  ,,,All HR Action Requests: IT CAFs - New Hires (KB 
Copy),,,,,,,,,,,,,
Sorted By:  ,,,Effective Date Descending,,,,,,,,,,,,,
Filtered By:  ,,,Initiator Filter: All Employees; Employee Filter: All 
Employees; Approver Filter: All Employees; HR Action = Hire Employee (Staff) 
- Step 2,,,,,,,,,,,,,
Date & Time:  ,,,01/06/2020 09:12p,,,,,,,,,,,,,
Generated By:  ,,,Haywood,,,,,,,,,,,,,
Company:  ,,,Corp Solutions(6122261),,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
New IT Item,StartDate,Effective Date,Employee Name,PC,Title,Supervisor 
Name,Manager 2 Name,O365,ID 
Badge,Computer,Avionte,GP,Hotspot,Tablet,TimeZone,HR Action
New,01/13/2020,02/03/2020,Elizabeth Anne Everts,Internal Staff/003 - 
003,Onboarding Specialist,Suzanne Mitchell,Angela 
Robbins,Yes,,No,Yes,No,No,No,Eastern,Hire Employee (Staff) - Step 2
New,01/13/2020,01/13/2020,Karla Ramirez,Internal Staff/204 - 003, 
Recruiter,Scott Clark,Shane Houser,Yes,,Standard 
Laptop,Yes,Yes,No,No,Central,Hire Employee (Staff) - Step 2
New,01/13/2020,01/06/2020,Megan Arreola,Internal Staff/221 - 
003,Recruiter,Elsa Muneton,Amanda Stewart,Yes,,No,Yes,No,No,No,Eastern,Hire 
Employee (Staff) - Step 2

1 Ответ

0 голосов
/ 07 января 2020

Замените вас на l oop на iterrows() вызов, как показано ниже:

        for i, r in newhire[mask].iterrows():
            server.sendmail(
                from_address,
                r["Email"],
                message.format(Employee=r["Employee"],
                   StartDate=r["StartDate"],
                               PC=r["PC"],
                               Title=r["Title"],
                               Email=r["Email"], 
                               Supervisor=r["Supervisor"]
                )
            )

EDIT1:

newhire[mask] в for a,....,c in newhire[mask] будет распакован содержимое newhire[mask] int a,....,c (весь фрейм данных). Что вы хотите сделать, это распаковать содержимое только одной строки. Для этого вы можете использовать newhire[mask].iterrows(), который в каждой строке возвращает свой индекс и сам экземпляр строки.

Вы также можете использовать itertuples(), как описано в этом вопросе Pandas для l oop через фрейм данных дает слишком много значений для распаковки

...