将Django模型存储在dataframe中,并从中获取列名,即使dataframe为空

2024-04-26 22:23:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有Django模型,它基于SQL表,我需要读取并存储在dataframe中,然后只检索一列来处理。对于第一次运行,表将是空的,因为哪个数据帧是空的[]

我需要模型返回带有列名的空白数据框,即使数据不在那里。我用来将模型检索到数据帧的当前代码行如下如下所示:你知道吗

dt = pd.DataFrame.from_records(my_table.objects.all().values())
my_val = dt.col1.iat[-1]

当前,代码失败,出现以下错误

AttributeError: 'DataFrame' object has no attribute 'col1'

Tags: 数据django代码from模型dataframesqlmy
1条回答
网友
1楼 · 发布于 2024-04-26 22:23:00

传递columns参数和列的名称,匹配数据的实际列的顺序。你知道吗

例如,如下所示:

dt = pd.DataFrame.from_records(my_table.objects.all().values(), columns['col1','col2','col3'])

引用参数文档:

columns : sequence, default None
    Column names to use. If the passed data do not have names
    associated with them, this argument provides names for the
    columns. Otherwise this argument indicates the order of the columns
    in the result (any names not found in the data will become all-NA
    columns)

相关问题 更多 >