python - 将 Pandas DataFrame 保存到 Django 模型

标签 python django pandas

我有存储在 pandas DataFrame 中的股票价格数据,如下所示(实际上它在面板中,但我将其转换为 DataFrame)

        date  ticker  close       tsr
0 2013-03-28  abc     22.81  1.000439
1 2013-03-28  def     94.21  1.006947
2 2013-03-28  ghi     95.84  1.014180
3 2013-03-28  jkl     31.80  1.000000
4 2013-03-28  mno     32.10  1.003125
...many more rows

我想将它保存在 Django 模型中,它看起来像这样(与列名匹配):

class HistoricalPrices(models.Model):
    ticker = models.CharField(max_length=10)
    date = models.DateField()
    tsr = models.DecimalField()
    close = models.DecimalField()

到目前为止我想到的最好的方法是使用它来保存它,其中 df 是我的 DataFrame:

entries = []
for e in df.T.to_dict().values():
    entries.append(HistoricalPrices(**e))
HistoricalPrices.objects.bulk_create(entries)

有没有更好的方法来保存它?

我看过django-pandas , 但看起来它只是从数据库中读取。

最佳答案

使用to_sql() 效率最高为 engine 使用适当的 connection 参数,并在你的 Django 应用程序中运行它,而不是遍历 DataFrame 和一次保存一个 model 实例:

from sqlalchemy import create_engine
from django.conf import settings

user = settings.DATABASES['default']['USER']
password = settings.DATABASES['default']['PASSWORD']
database_name = settings.DATABASES['default']['NAME']

database_url = 'postgresql://{user}:{password}@localhost:5432/{database_name}'.format(
    user=user,
    password=password,
    database_name=database_name,
)

engine = create_engine(database_url, echo=False)
df.to_sql(HistoricalPrices, con=engine)

关于python - 将 Pandas DataFrame 保存到 Django 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37688054/

相关文章:

python - 在 python 中使用 bson.json_util.loads 时如何忽略时区?

python - 大型文本文件中最快的文本搜索方法

python - 在 python 中读取 csv 列返回错误

python - 将 NaN 值填充到缺少某些时间范围的连续时间序列数据中

python - 如何根据 Python 中另一个列表的(子列表)索引对列表进行分区

python - 用 SVD 计算 spinv

python - 导入错误 : No module named context_processors

python - Pandas:read_table删除带有 '##'但不是 '#<string>'的注释行?

python - 无法从 Django 应用程序父目录中的子目录导入模块

python - django-admin 中的动态表单