Created
July 26, 2018 23:05
-
-
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()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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