pandas.read_csv:OperationalError:table没有名为1的列

时间:2016-12-16 21:20:51

标签: python sqlite csv pandas

enter image description here

我正在尝试使用以下命令将csv上传到Windows上的sqllite表:

sqllite表和csv具有相同的字段名称,并以:

开头
CREATE TABLE test2 (
id INTEGER NOT NULL, 
"case" TEXT, 
 ......
PRIMARY KEY (id), 
UNIQUE ("case")
)

我有以下课程:

class Sqllite_utilities(object):

    def __init__(self, db_path, table_name):
        self.db_path = db_path
        self.table_name = table_name

    def upload_csv_to_table(self, path_to_csvfile):
        conn = sqlite3.connect(self.db_path)
        df = pandas.read_csv(path_to_csvfile)
        df.to_sql(self.table_name, conn, if_exists='append', index_label='id')

在命令行:

s = Sqllite_utilities(settings.SETTINGS_PATH+"\\data.db",'test2')

In[3]: s.upload_csv_to_table('C:\Users\ne\Desktop\jtest.csv')
C:\lib\site-packages\pandas\core\generic.py:1201: UserWarning: The spaces in these column names will not be changed. In pandas versions < 0.14, spaces were converted to underscores.
  chunksize=chunksize, dtype=dtype)
Traceback (most recent call last):
  File "C:\lib\site-packages\IPython\core\interactiveshell.py", line 2885, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-3-b530f5199977>", line 1, in <module>
    s.upload_csv_to_table('C:\Users\dnir\Desktop\jtest.csv')
  File "F:\ENVS\r2\j1\utilities.py", line 41, in upload_csv_to_table
    df.to_sql(self.table_name, conn, if_exists='append', index_label='id')
  File "C:\lib\site-packages\pandas\core\generic.py", line 1201, in to_sql
    chunksize=chunksize, dtype=dtype)
  File "C:\lib\site-packages\pandas\io\sql.py", line 470, in to_sql
    chunksize=chunksize, dtype=dtype)
  File "C:\lib\site-packages\pandas\io\sql.py", line 1503, in to_sql
    table.insert(chunksize)
  File "C:\lib\site-packages\pandas\io\sql.py", line 664, in insert
    self._execute_insert(conn, keys, chunk_iter)
  File "C:\lib\site-packages\pandas\io\sql.py", line 1291, in _execute_insert
    conn.executemany(self.insert_statement(), data_list)
OperationalError: table test2 has no column named 1

我做错了什么?

编辑:我认为你得到了它,我收到了一个新的错误,我将分别调查:

  df.to_sql(self.table_name, conn, if_exists='append', index_label='id')
File "C:\lib\site-packages\pandas\core\generic.py", line 1201, in to_sql
  chunksize=chunksize, dtype=dtype)
File "C:\lib\site-packages\pandas\io\sql.py", line 470, in to_sql
  chunksize=chunksize, dtype=dtype)
File "C:\lib\site-packages\pandas\io\sql.py", line 1503, in to_sql
  table.insert(chunksize)
File "C:\lib\site-packages\pandas\io\sql.py", line 642, in insert
  keys, data_list = self.insert_data()
File "C:\lib\site-packages\pandas\io\sql.py", line 609, in insert_data
  "duplicate name in index/columns: {0}".format(err))
 ValueError: duplicate name in index/columns: cannot insert id, already exists

1 个答案:

答案 0 :(得分:2)

问题在于索引列,Pandas将数据帧的索引作为列&#39;索引&#39;。如果你不想要没有它的插入记录,试试这个;

df.to_sql(...,index = False)