У меня есть файл .csv с> 100 столбцами и несколькими тысячами строк:
> Datetime A B C D E ... FA FB
> 01.01.2014 00:00 15,15 15,15 32,43 15,15 33,27 82,59 1,38
> 01.01.2014 01:00 12,96 12,96 32,49 12,96 30,07 82,59 1,38
> 01.01.2014 02:00 12,09 12,09 28,43 12,09 23,01 82,59 1,38
> 01.01.2014 03:00 11,7 11,7 27,63 11,7 11,04 82,59 1,38
> 01.01.2014 04:00 11,66 11,66 25,99 11,66 9,09 82,59 1,38
> ... ... ... ... ... ... ... ...
> 01.10.2018 23:00 9,85 9,85 17,2 9,85 10,44 92,15 1,09
Теперь мне нужно извлечь эти данные по столбцам и экспортировать их в базу данных sqlite3 следующим образом:
Datetime and A
Datetime and B
Datetime and C
...
Datetime and FB
Чтобы получить таблицу базы данных, которая выглядит следующим образом:
Datetime Value ID
> 01.01.2014 00:00 15,15 A
> 01.01.2014 01:00 12,96 A
> 01.01.2014 02:00 12,09 A
> ... ... ...
> 01.01.2014 00:00 15,15 FB
> 01.01.2014 01:00 12,96 FB
> 01.01.2014 02:00 12,09 FB
Мне удается записать некоторые данные, используя следующий код:
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Numeric, DateTime
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import pandas as pd
Base = declarative_base()
# Declaration of the class in order to write into the database. This structure is standard and should align with SQLAlchemy's doc.
class Values_1(Base):
__tablename__ = 'Timeseries_Values'
ID = Column(Integer, primary_key=True)
Date = Column(DateTime, primary_key=True)
Value = Column(Numeric)
def main(fileToRead):
# Set up of the table in db and the file to import
fileToRead = r'data.csv'
tableToWriteTo = 'Timeseries_Values'
df = pd.read_csv(fileToRead, sep=';', decimal=',', parse_dates=['Date'], dayfirst=True)
df.columns = ['Datetime', 'A']
engine = create_engine('sqlite:///data.db')
conn = engine.connect()
metadata = sqlalchemy.schema.MetaData(bind=engine, reflect=True)
table = sqlalchemy.Table(tableToWriteTo, metadata, autoload=True)
# Open the session
Session = sessionmaker(bind=engine)
session = Session()
conn.execute(table.insert(), listToWrite)
session.commit()
session.close()
Так что это работает для одной комбинации («Дата и время»), но как я могу автоматически добавить все остальные комбинации?
Спасибо заранее.