I pulled an SQL Query result from BigQyery with Python, and stored the result is in a dataframe, one of the fields event_params has been saved as a list of sets as follows
[{'key': 'update_with_analytics', 'value': {'string_value': None, 'int_value': 0.0, 'float_value': None, 'double_value': None}}
{'key': 'firebase_event_origin', 'value': {'string_value': 'auto', 'int_value': None, 'float_value': None, 'double_value': None}}
{'key': 'firebase_conversion', 'value': {'string_value': None, 'int_value': 1.0, 'float_value': None, 'double_value': None}}
{'key': 'previous_first_open_count', 'value': {'string_value': None, 'int_value': 0.0, 'float_value': None, 'double_value': None}}]
I would like to store the values of the above set in several columns like so:
event_params.key | event_params.value.string_value | event_params.value.int_value | event_params.value.float_value | event_params.value.double_value
This is my python code
import google.oauth2.service_account as service_account
from google.cloud import bigquery
import datetime
from time import perf_counter
import sqlalchemy
import pandas as pd
today = datetime.datetime.today()
yesterday = today - datetime.timedelta(days=2)
numdays = 2
dateList = []
gcp_project = '***'
bqtable = 'analytics_###'
client = bigquery.Client(project=gcp_project,credentials=credentials)
table_ref = client.dataset(bqtable)
for x in range (0, numdays):
date = yesterday - datetime.timedelta(days = x)
date_str = date.strftime('%Y%m%d')
dateList.append(date_str)
df = pd.DataFrame()
for i in dateList:
query = f"""SELECT * FROM `***.analytics_####.events_{i}`"""
def bq2bi(sql):
query = client.query(sql)
query_results = query.result()
return query_results.to_dataframe()
df = pd.concat([df,bq2bi(query)])
main_df_2 = df.applymap(str)
print(main_df_2)
try:
main_df_2.to_sql(con=con, name='Firebase', if_exists='replace')
except:
print('database failed to update')
else:
print("database updated")
Stop = perf_counter()
print("Script ran in",round(Stop-Start,2),"seconds")
if there is a better way to pull the data from bigquery without it being converted to a list of sets please do advise!