Csv数据库:Pandas-CSV到SQL数据库

关于Csv数据库的问题,在dataframe from csv中经常遇到, 我现在已经解决了我遇到的问题。非常感谢评论者。我修改后的和现在运行的代码如下:

我现在已经解决了我遇到的问题。非常感谢评论者。我修改后的和现在运行的代码如下:

import pandas as pd
from sqlalchemy import *
from sqlalchemy_utils import *
#create engine and connect to DB
engine = create_engine("mysql://root:@127.0.0.1:3306/polution")
if not database_exists("mysql://root:@127.0.0.1:3306/polution"):
  create_database("mysql://root:@127.0.0.1:3306/polution")
else:
  engine.connect()
#create tables and define
metadata_obj=MetaData()
sites = Table('sites', metadata_obj,
        Column('SiteID',Integer, primary_key=True,nullable=False),
        Column('Location',Text(48)),
        Column('geo_point_2d', String(150)))
metadata_obj.create_all(engine)
#read in csv, set specific table-relevant dataframes, push to database
df = pd.read_csv("cleanedcropped_bristol-air-quality-data.csv", sep=",", p_dates=["Date Time","DateStart","DateEnd"],low_memory=False)
dfsites=df[["SiteID", "Location", "geo_point_2d"]][:100]
dfsites.to_sql(name='sites',con=engine,index=False,if_exists='replace',)`

我真的很新,这一切,我目前正在努力的东西,是伸展我的技能和理解,所以我会感谢一些帮助,请。

我有一个大的 csv 文件,我想读入一个 pandas 数据框,然后将内容推送到已经创建的由多个实体组成的 mariadb 数据库。目前,我正在尝试使用 to_sql () 函数尝试此操作。运行脚本似乎并没有实际将任何数据从数据帧推送到数据库中的实体,因为它在运行后仍然为空。

FYI 数据框包含多个列,只有其中一些我想推到相关实体。

任何指针非常感谢!

conn = sqlalchemy .create_engine("mysql://root:@127.0.0.1:3306")  
cur = conn.cursor()
cur.execute(databse = "pollution")
sites= """CREATE TABLE IF NOT EXISTS `sites`
  (`siteID` INT(20) NOT NULL,
  `Location` VARCHAR(48) NULL,
  `geo_point_2d` VARCHAR(150) NULL,
  PRIMARY KEY (`siteID`))"""
cur.execute(sites)
df = pd.read_csv("data.csv", sep=",", p_dates ["DateTime","DateStart","DateEnd"],low_memory=False)
df.to_sql('sites', conn, if_exists='append',index=False)
conn.commit()
0

尝试在创建表后提交您的执行。

cur.execute(sites) conn.commit
0

它看起来可能会失败,因为您尝试插入的列不是站点中描述的架构的一部分-& gt;“DateTime”,“DateStart”,“DateEnd”。如果是这种情况,请在站点字符串中包含这些列。否则,您需要将数据框架子集化。

如果你不能得到这个与 pd.to_sql () 命令一起工作,这里有一个解决方法。你需要创建一个 Table 对象。如果它是一个已经存在的数据库表,请确保将 'autoload_with' = 设置为你的引擎 (我认为这对你来说是 'conn')。

将数据帧转换为面向记录列表(字典列表)的字典,每行将是其自己的字典。每个键将是列名,值将是与列对应的特定行值。

然后,您可以简单地将字典列表插入数据库。

engine = sqlalchemy .create_engine("mysql://root:@127.0.0.1:3306")  
cur = engine.cursor()
cur.execute(databse = "pollution")
sites= """CREATE TABLE IF NOT EXISTS `sites`
  (`siteID` INT(20) NOT NULL,
  `Location` VARCHAR(48) NULL,
  `geo_point_2d` VARCHAR(150) NULL,
  PRIMARY KEY (`siteID`))"""
cur.execute(sites)
df = pd.read_csv("data.csv", sep=",", p_dates ["DateTime","DateStart","DateEnd"],low_memory=False)
# specify which columns you want, as a string, and within the double brackets.
df = df[['siteID,'Location','geo_point_2d']]
"""or if you have too many columns to manually put in, but have a specific range in mind.
this is telling pandas to get the first four columns
when you see this -> : -> it means start:stop """
df = df.iloc[,:4]
metadata_obj = MetaData()
records = df.to_dict(orient='records')
#note rather than creating a sql string you can also create the Table with a table object, checkout the sqlalchemy tutorial I linked
sites = Table('sites', metadata_obj, autoload_with =engine)
with engine.connect() as conn:
   conn.execute(sites.insert(),records)

我还认为,如果您通读 sqlalchemy-coredocumentation会有所帮助。本教程将向您展示如何使用所需的列创建 Table 对象。

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(158)
冒险岛数据:基于选择的冒险游戏的数据结构
上一篇
数据比对:MUSCLE多序列比对
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(35条)