将Pandas DataFrame保存到Django模型 [英] Saving a Pandas DataFrame to a Django Model

查看:579
本文介绍了将Pandas DataFrame保存到Django模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have stock price data that is stored in a pandas DataFrame as shown below (actually it was in a panel, but I converted it to a 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模型中,该模型如下所示(与列名称匹配):

I want to save this in a Django model, which looks like this (matches the column names):

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

到目前为止,我所能提出的最好的办法是使用它来保存它,其中df是我的DataFrame:

The best I've come up so far is using this to save it, where df is my DataFrame:

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

是否有更好的方法来保存此内容?

Is there a better way to save this?

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

I've looked at django-pandas, but looks like it just reads from the DB.

推荐答案

使用

It would be most efficient to use to_sql() with appropriate connection parameters for the engine, and run this inside your Django app rather than iterating through the DataFrame and saving one model instance at a time:

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)

这篇关于将Pandas DataFrame保存到Django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆