熊猫导入不插入所有行

时间:2019-03-13 12:22:31

标签: mysql python-3.x pandas csv

我正在通过以下方式导入包含3300行数据的.csv文件:

myCSVfile = pd.read_csv(csv_file)
myCSVfile.to_sql(con=engine, name='foo', if_exists='replace')

成功导入后,我在表上执行“ select * from ...”查询,该查询返回3100行,那么缺少的200行在哪里?

我假设存在无法读取的损坏数据,我进一步假设这些数据将被熊猫跳过。但是,没有警告,日志或消息明确表示。该脚本正常执行。

有人遇到过类似的问题吗?还是我错过了一些显而易见的东西?

1 个答案:

答案 0 :(得分:1)

尽管问题未指定engine,但我们假设它是sqlite3

以下可重新运行的代码显示DataFrame.to_sql()创建一个sqlite3表,并在其上放置一个索引。这是数据框索引中的数据。

从字面上看问题代码,csv应该使用RangeIndex导入到DataFrame中,这将是唯一的序数。因此,如果csv中的行数与加载到sqlite3表中的行数不匹配,应该感到惊讶。

因此,有两件事要做:验证csv是否正确导入。这可能是问题所在,因为源自人为操作的电子表格的格式不正确的csv文件在出于各种原因被代码处理时,经常会失败。但这不可能在这里回答,因为我们不知道输入数据。

但是,DataFrame.to_sql()的作用应排除在外。为此,可以传递method。它可以用于查看DataFrame.to_sql()对DataFrame数据的处理,然后再将其交给SQL engine

import csv
import pandas as pd
import sqlite3

def dump_foo(conn):
    cur = conn.cursor()
    cur.execute("SELECT * FROM foo")
    rows = cur.fetchall()
    for row in rows:
        print(row)

conn = sqlite3.connect('example145.db')

csv_data = """1,01-01-2019,724
2,01-01-2019,233,436
3,01-01-2019,345
4,01-01-2019,803,933,943,923,954
4,01-01-2019,803,933,943,923,954
4,01-01-2019,803,933,943,923,954
4,01-01-2019,803,933,943,923,954
4,01-01-2019,803,933,943,923,954
5,01-01-2019,454
5,01-01-2019,454
5,01-01-2019,454
5,01-01-2019,454
5,01-01-2019,454"""

with open('test145.csv', 'w') as f:
    f.write(csv_data)

with open('test145.csv') as csvfile:
    data = [row for row in csv.reader(csvfile)]
df = pd.DataFrame(data = data)

def checkit(table, conn, keys, data_iter):
    print "What pandas wants to put into sqlite3"
    for row in data_iter:
        print(row)

# note, if_exists replaces the table and does not affect the data
df.to_sql('foo', conn, if_exists="replace", method=checkit)
df.to_sql('foo', conn, if_exists="replace")
print "*** What went into sqlite3"
dump_foo(conn)
相关问题