Skip to content

Instantly share code, notes, and snippets.

@pablocastelo
Last active May 30, 2022 18:05
Show Gist options
  • Save pablocastelo/9e94ed5596853b313685e313786f0141 to your computer and use it in GitHub Desktop.
Save pablocastelo/9e94ed5596853b313685e313786f0141 to your computer and use it in GitHub Desktop.
pandas DataFrame to SQL Values
def df_to_values(df, name = 'tmp', first = True):
template = "{name} as (select * from (values {values}) as t ({columns}))"
if first: template = "with {}".format(template)
names = df.columns
values = df.values.tolist()
rows = []
for items in values:
row = []
for i in items:
if isinstance(i, datetime.date):
i = f"date('{i}') at time zone 'UTC'"
elif isinstance(i, str):
i = "'{}'".format(i)
else:
i = str(i)
row.append(i)
rows.append("""({})""".format(', '.join(row)))
v = ', '.join(rows)
c = ', '.join(names)
r = template.format(values = v, columns = c, name = name)
return r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment