[英]Pandas.io.sql read_frame() and to_csv() methods show the output with an additional column
[英]pandas csv to psql: additional column is being generated in output (?)
我的.csv生成的psql数据库正在创建,且带有额外的列,但我不知道为什么...
in.csv:
Box,Color,Contents`
1,Blue,"thing one [version 1] [dd/mm/yyyy]
thing two [version 1] [dd/mm/yyyy]
thing three [version 1] [dd/mm/yyyy]
2,Red,thing four [version 1] [dd/mm/yyyy]
3,Green,"thing five [version 1] [dd/mm/yyyy]
thing six [version 1] [dd/mm/yyyy]
convert.py(已编辑)
## begin imports
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, create_database
import pandas as pd
import numpy as np
import re
import sys
import csv
import time
## begin cellmaxmod
csv.field_size_limit(sys.maxsize)
maxInt = sys.maxsize
decrement = True
while decrement:
# decrease the maxInt value by factor 10
# as long as the OverflowError occurs.
decrement = False
try:
csv.field_size_limit(maxInt)
except OverflowError:
maxInt = int(maxInt/10)
decrement = True
## begin csv2df
df = pd.read_csv('in.csv', encoding='utf-8', engine='python', na_values=['.'])
## begin df2csv
df.to_csv('out.csv')
## begin csv2psql
class MyDB(object):
def __init__(self):
self.params = config()
def create_new_db(self, newdb):
user, host, port = self.params['user'], self.params['host'], self.params['port']
pw = self.params['password']
url = 'postgresql://{}:{}@{}:{}/{}'
url = url.format(user, pw, host, port, newdb)
self.engine = create_engine(url, client_encoding='utf8')
if not database_exists(self.engine.url):
create_database(self.engine.url)
# print(database_exists(engine.url))
def df2postgres(engine, df):
con = engine.connect()
df.to_sql(name='data', con=con, if_exists='replace', index=True, chunksize=10)
return con
if __name__ == '__main__':
testdb = MyDB()
testdb.create_new_db('converted')
engn = testdb.engine
df = pd.read_csv('out.csv', encoding='utf-8', engine='python', na_values=['.'])
pd.isnull(df)
out.csv(注意新列):
,Box,Color,Contents
0,1,Blue,"thing one [version 1] [dd/mm/yyyy]
thing two [version 1] [dd/mm/yyyy]
thing three [version 1] [dd/mm/yyyy]
1,2,Red,thing four [version 1] [dd/mm/yyyy]
2,3,Green,"thing five [version 1] [dd/mm/yyyy]
thing six [version 1] [dd/mm/yyyy]
psql数据库的pg4admin屏幕截图:
问题:第二列在哪里? “ Unamed:0”来自何处?在创建数据库之前,如何在out.csv中停止其生成或脚本对其进行安全删除?
〜tnx。
我的.csv生成的psql数据库正在创建,且带有额外的列,但我不知道为什么...
out.csv
中的该额外列实际上是数据帧索引。 要删除它,必须将index=False
参数值传递给to_csv()
方法。
df.to_csv('out.csv', index=False)
这将生成没有附加列的out.csv
文件。
希望能帮助到你 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.