Difference between revisions of "Pandas snippets"
Jump to navigation
Jump to search
(Created page with "# DataFrame to JSON for SQL This will do it for all columns all rows. ``` for i in df.columns: df[i] = [json.dumps(x) for x in df[i]] df.to_sql(name='fb1', con=cnx, index=F...") |
|||
Line 2: | Line 2: | ||
This will do it for all columns all rows. | This will do it for all columns all rows. | ||
+ | ``` | ||
+ | for i in df.columns: | ||
+ | for i in df.columns: df[i] = df[i].astype("string") | ||
+ | ``` | ||
+ | |||
+ | This leave quotes around everything - not good | ||
``` | ``` | ||
for i in df.columns: | for i in df.columns: | ||
Line 14: | Line 20: | ||
for i in df.columns: | for i in df.columns: | ||
− | df[i] = [ | + | for i in df.columns: df[i] = df[i].astype("string") |
cnx = sqlite3.connect(f"db.sqlite3") | cnx = sqlite3.connect(f"db.sqlite3") | ||
df.to_sql(name='table1', con=cnx, index=False) | df.to_sql(name='table1', con=cnx, index=False) | ||
``` | ``` |
Latest revision as of 21:40, 7 September 2023
DataFrame to JSON for SQL
This will do it for all columns all rows.
for i in df.columns: for i in df.columns: df[i] = df[i].astype("string")
This leave quotes around everything - not good
for i in df.columns: df[i] = [json.dumps(x) for x in df[i]] df.to_sql(name='fb1', con=cnx, index=False)
Assuming dataframe df
import pandas import sqlite3 for i in df.columns: for i in df.columns: df[i] = df[i].astype("string") cnx = sqlite3.connect(f"db.sqlite3") df.to_sql(name='table1', con=cnx, index=False)