KeyError : 0 - 在数据帧中循环时。

问题描述 投票:0回答:1

先谢谢大家的帮助。 我对这个还是很陌生,我真的不知道自己在做什么。 我试过很多方法,但一直出现错误。 我试过使用iterrows,iloc,loc等等,都没有成功。 我不明白如何获取每一行的数据并使用该行的值来发送邮件。

代码。

email_list 
+---+-------------+-----------------+------+------------+---------------------------+---------------+----------------------------------+
|   | Client Name | Staff Name      | Role | Due Date   | Submission ID             | Staff Email   | Generated Due Docs ID            |
+---+-------------+-----------------+------+------------+---------------------------+---------------+----------------------------------+
| 1 | H.Pot       | JohannaNameLast | IP   | 2020-04-01 | H.POT-Johanna-IP-4/1/2020 | [email protected] | h.potjohannanamelastip2020-04-01 |
+---+-------------+-----------------+------+------------+---------------------------+---------------+----------------------------------+
| 2 | S.Man       | DaveSmith       | TS   | 2020-04-01 | S.MAN-David-TS-4/1/2020   | [email protected] | s.mandabc2020-04-01              |
+---+-------------+-----------------+------+------------+---------------------------+---------------+----------------------------------+
| 3 | S.Man       | LouisLastName   | IP   | 2020-04-01 | S.MAN-Louis-IP-4/1/2020   | [email protected] | s.manlouislastnameip2020-04-01   |
+---+-------------+-----------------+------+------------+---------------------------+---------------+----------------------------------+
| 5 | T.Hul       | KellyDLastName  | IP   | 2020-04-01 | T.HUL-Kelly-IP-4/1/2020   | [email protected] | t.hulkelleydlastnameip2020-04-01 |
+---+-------------+-----------------+------+------------+---------------------------+---------------+----------------------------------+
# Get all the Names, Email Addresses, roles and due dates.
all_clients = email_list['Client Name']
all_staff = email_list['Staff Name']
all_roles = email_list['Role']
#all_types = email_list['Form Type']
all_due_dates = email_list['Due Date']
all_emails = email_list['Staff Email']

for idx in range(len(email_list)):
    # Get each records name, email, subject and message
    client = all_clients[idx]
    staff = all_staff[idx]
    role = all_roles[idx]
    #form_type = all_types[idx]
    due_date = all_due_dates[idx]
    email_address = all_emails[idx]

    # Get all the Names, Email Addresses, roles and due dates.
    subject = f"Your monthly summary was Due on {due_date} Days For {client.upper()}"
    message = f"Hi {staff.title()}, \n\nThe {form_type} is due in {due_date} days for {client.upper()}.  Please turn it in before the due date. \n\nThanks, \n\nJudy"


full_email = ("From: {0} <{1}>\n"
                  "To: {2} <{3}>\n"
                  "Subject: {4}\n\n"
                  "{5}"
                  .format(your_name, your_email, staff, email_address, subject, message))
    # In the email field, you can add multiple other emails if you want
    # all of them to receive the same text
try:
    server.sendmail(your_email, [email_address], full_email)
    print('Email to {} successfully sent!\n\n'.format(email_address))
except Exception as e:
    print('Email to {} could not be sent :( because {}\n\n'.format(email_address, str(e)))

# Close the smtp server
server.close()
python pandas loops keyerror
1个回答
0
投票

提取所有的列,然后从每一个这样的变量(持有一个列)中获取各自的元素,这是一个糟糕的模式。

请使用下面的模式。

for idx, row in email_list.iterrows():
    row.Role
    row['Staff Name']

如果你不使用 idx确切地说 _ 而不是。

这个变体比你的快多了。上面的代码实际上是在这里执行一个 单一 迭代(在行上),而你的代码则是在行号上进行单次迭代。

  • 也是对行数进行单次迭代。
  • 但你的代码会执行 n 查找,对于单个元素,用特定的索引在 每列.

让我们回到我的代码示例.有两个变体来访问当前行的元素。

  • row.Role - 如果列名中不包含 "特殊 "字符(如空格)。
  • row['Staff Name'] - 在其他(更复杂)的情况下。

而为什么你会得到 KeyError: 0.

请注意。

  • 你的行的索引是以 1 最左边一栏,没有标题)。
  • 但在你的圈子里 idx 始于 0,
  • 对每一个 "列变量 "的访问实际上只是由指数值而不是 "想要 "元素的整数位置。

因此,错误发生在循环的第一圈,当你。

  • 当你: idx == 0,
  • 无列变量 系列)包含一个元素withindex == 0.

其实 熊猫 这里使用了两个不同的名字(钥匙指数值)为同样的事情,所以这条信息在多大程度上是可读的,是可以讨论的.你无能为力。你只需要知道它。

或者,如果你出于某种原因想保持你的代码的当前版本,那么只需修改 对于 指令到。

for idx in range(1, len(email_list) + 1):
    ...

那么这个循环将从 idx == 1 就不会出现错误,只要你把索引设为 连续 数字,从1开始。

但我注意到,你的索引。

  • 是以 1, 23 (到目前为止还不错)。
  • 但这样一来,就出现了一个 "缺口",你没有索引为 4.

1
投票

email_list.iterrows() 返回一个迭代器,产生索引以及该索引在数据框中的行。所以迭代可以这样做。

for idx, row in email_list.iterrows():
    # Get each records name, email, subject and message
    client = row['Client Name']
    staff = row['Staff Name']
    role = row['Role']
    #form_type = row['Form Type']
    due_date = row['Due Date']
    email_address = row['Staff Email']

    # Get all the Names, Email Addresses, roles and due dates.
    subject = f"Your monthly summary was Due on {due_date} Days For {client.upper()}"
    message = f"Hi {staff.title()}, \n\nThe {form_type} is due in {due_date} days for {client.upper()}.  Please turn it in before the due date. \n\nThanks, \n\nJudy"

你可以了解更多关于pandas.DataFrame.iterrows() 此处

© www.soinside.com 2019 - 2024. All rights reserved.