Skip to content

Instantly share code, notes, and snippets.

@emesterhazy
Created July 26, 2018 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emesterhazy/c31f2a71057065111f9e3cb394abefdd to your computer and use it in GitHub Desktop.
Save emesterhazy/c31f2a71057065111f9e3cb394abefdd to your computer and use it in GitHub Desktop.
Return a dictionary of SQL datatypes inferred from a pandas dataframe for use with df.to_sql()
import sqlalchemy as sa
def sql_type(data_frame):
"""Return a dict of sql types inferred from pandas type"""
type_dict = {}
for i, j in zip(data_frame.columns, data_frame.dtypes):
if 'float' in str(j):
type_dict.update({i: sa.types.Float(precision=5,
asdecimal=True)})
elif 'object' in str(j):
type_dict.update({i: sa.types.NVARCHAR(length=1000)})
elif 'datetime' in str(j):
type_dict.update({i: sa.types.DateTime()})
elif 'int' in str(j):
type_dict.update({i: sa.types.INT()})
else:
type_dict.update({i: sa.types.NVARCHAR(length=1000)})
return type_dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment