属性错误 - 'Div'对象没有属性'set_index'



我正在尝试运行以下代码:

def parse_data(contents, filename):
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
try:
if 'csv' in filename:
# Assume that the user uploaded a CSV or TXT file
df = pd.read_csv(
io.StringIO(decoded.decode('utf-8')))
elif 'xls' in filename:
# Assume that the user uploaded an excel file
df = pd.read_excel(io.BytesIO(decoded))
elif 'txt' or 'tsv' in filename:
# Assume that the user upl, delimiter = r's+'oaded an excel file
df = pd.read_csv(
io.StringIO(decoded.decode('utf-8')), delimiter = r's+')
except Exception as e:
print(e)
return html.Div([
'There was an error processing this file.'
])
return df
def update_graph(contents, filename):
fig = {
'layout': go.Layout(
plot_bgcolor=colors["graphBackground"],
paper_bgcolor=colors["graphBackground"])
}
if contents:
contents = contents[0]
filename = filename[0]
df = parse_data(contents, filename)
df = df.set_index(df.columns[0])
fig['data'] = df.iplot(asFigure=True, kind='scatter', mode='lines+markers', size=1)

return fig

得到这个错误:

Traceback (most recent call last):
File "/Users/.../PycharmProjects/pythonProject2/main.py", line 93, in update_graph
df = df.set_index(df.columns[0])
AttributeError: 'Div' object has no attribute 'set_index'

有什么想法吗?非常感谢!

所有问题都与parse_data()有关。若它不能读取文件,那个么它会运行return html.Div(),所以运行df = parse_data()意味着df = html.Div(),稍后您不会检查是否真的在df中获得了数据,而df.set_index()意味着html.Div().set_index()

也许最好使用return None,并在df = parse_data()之后检查

def parse_data(contents, filename):
# ... code ...
try:
# ... code ...
except Exception as e:
print(e)
return None
return df

以及后来的

df = parse_data(contents, filename)
if df is None:
html.Div(['There was an error processing this file.'])
else:
df = df.set_index(df.columns[0])
fig['data'] = df.iplot(asFigure=True, kind='scatter', mode='lines+markers', size=1)

但当fig['data']无法读取文件时,它仍然会出现问题。

我不能测试你的代码,但也许它应该将Div分配给fig['data']

if df is None:
fig['data'] = html.Div(['There was an error processing this file.'])
else:
df = df.set_index(df.columns[0])
fig['data'] = df.iplot(asFigure=True, kind='scatter', mode='lines+markers', size=1)

最新更新