gpt4 book ai didi

python - 创建一个处理错误的函数来处理 Pandas 过滤并将值导出到Excel单元格

转载 作者:行者123 更新时间:2023-12-03 08:21:11 32 4
gpt4 key购买 nike

我创建了一个python程序,该程序从许多Web来源中抓取数据并将结果汇​​总到一个数据框中。我现在正尝试将汇总表的结果放入Excel电子表格,并定义将哪些数据放入哪些单元格。

我的问题是,有时数据会从数据框中丢失,因为它在网站上不存在。当我尝试在 Pandas 数据框中过滤/定位它时,这将导致IndexError。

为了解决此问题,我创建了一个try/except语句,以在发生IndexError时向Excel返回空白值。但是,这意味着每次我想向Excel单元格中插入一个值时,都必须重复代码。为了减少行数,我决定编写一个函数来执行错误处理和值的插入,而不是执行多个try/except语句。问题在于,该函数没有按照我期望的方式运行,如下面的#可以工作和#不能工作示例所示。

我希望能够使用cell_insert(cell,data)将数据插入到单元格中,并能够为我处理一些特定的错误。也许我误会了某种句法?

import pandas as pd

wb = Workbook()
ws = wb.active

df_data = {
'year_month': ['2019-06', '2019-06', '2019-06', '2019-06', '2019-06'],
'lead_source': ['C', 'IH', 'INH', 'INH', 'MV'],
'status': ['Lead', 'Lead', 'Lead', 'Refund', 'Lead'],
'leads': [12, 7, 51, 2, 15],
'total': [140, 280, 918, 36, 150]
}
df = pd.DataFrame(df_data)

# Does work
try:
ws['A1'] = df[(df['lead_source'] == 'C') & (df['status'] == 'Lead')].iloc[0]['total']
except IndexError:
ws['A1'] = ''

try:
ws['A2'] = df[(df['lead_source'] == 'C') & (df['status'] == 'Refund')].iloc[0]['total']
except IndexError:
ws['A2'] = ''

# Doesn't work
# def cell_insert(cell, data):
# try:
# ws[cell] = data
# except IndexError:
# ws[cell] = ''
#
# cell_insert('A2', df[(df['lead_source'] == 'C') & (df['status'] == 'Refund')].iloc[0]['total'])

wb.save("stackoverflow.xlsx")

最佳答案

当您调用该函数时,您甚至在将数据传递给该函数之前都会遇到错误。如果第二个参数引发IndexError,它将永远不会在函数中传递。

例如,尝试:

print(df[(df['lead_source'] == 'C') & (df['status'] == 'Refund')].iloc[0]['total'])
#This will not print and return an error because the print function will never receive the input because it evaluates to an error.

一种公认的笨拙解决方法是将其作为字符串传递并使用 eval
def cell_insert(cell, data):
#pass data as a string
try:
eval(data)
except IndexError:
data="''"
ws[cell] = eval(data)

您可以在条目周围加上引号来称呼它
cell_insert('A2', "df[(df['lead_source'] == 'C') & (df['status'] == 'Refund')].iloc[0]['total']")
#this should work

重要的是不要混淆单引号和双引号。外部使用双引号,对数据框的实际调用使用单引号,反之亦然。

关于python - 创建一个处理错误的函数来处理 Pandas 过滤并将值导出到Excel单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56429390/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com