使用pandas将数据存储在django创建的数据库之中,具体代码示意如下:
from django.db import models
from django.conf import settings
from .available import df_available
import sqlite3
engine = settings.DATABASES['default']['NAME']
# Create your models here.
class Stocks(models.Model):
ticker = models.CharField(max_length=16, primary_key=True)
beta = models.FloatField(default=1.0)
def __str__(self):
return self.ticker
cnxn = sqlite3.connect(engine)
df_final.to_sql(‘api_stocks’, con=cnxn, if_exists=’replace’, index=False)
将csv数据写入MySQL数据库,示意代码如下:
# -*- coding: utf-8 -*-
# 导入必要模块
import pandas as pd
from sqlalchemy import create_engine
# 初始化数据库连接,使用pymysql模块
engine = create_engine(‘mysql+pymysql://root:147369@localhost:3306/mydb’)
# 读取本地CSV文件
df = pd.read_csv(“E://mpg.csv”, sep=’,’)
# 将新建的DataFrame储存为MySQL中的数据表,不储存index列
df.to_sql(‘mpg’, engine, index= False)
print(“Write to MySQL successfully!”)
转载请注明:王杭州的个人网页 » pandas django数据处理 [zz]