Question: import psycopg2 import pandas as pd # Make our connection/cursor function def get_conn_cur(): # define function name and arguments (there aren't any) # Make a
import psycopg2
import pandas as pd
# Make our connection/cursor function
def get_conn_cur(): # define function name and arguments (there aren't any)
# Make a connection
conn = psycopg2.connect(
host="ticketsdbinstance.cnt7cm8tgir1.us-west-1.rds.amazonaws.com",
database="sales_db",
user="postgres",
password="ISTA322SALESDB",
port='5432')
cur = conn.cursor() # Make a cursor after
return(conn, cur) # Return both the connection and the cursor
# Same run_query function
def run_query(query_string):
conn, cur = get_conn_cur() # get connection and cursor
cur.execute(query_string) # executing string as before
my_data = cur.fetchall() # fetch query data as before
# here we're extracting the 0th element for each item in cur.description
colnames = [desc[0] for desc in cur.description]
cur.close() # close
conn.close() # close
return(colnames, my_data) # return column names AND data
# Column name function for checking out what's in a table
def get_column_names(table_name): # arguement of table_name
conn, cur = get_conn_cur() # get connection and cursor
# Now select column names while inserting the table name into the WERE
column_name_query = """SELECT column_name FROM information_schema.columns
WHERE table_name = '%s' """ %table_name
cur.execute(column_name_query) # exectue
my_data = cur.fetchall() # store
cur.close() # close
conn.close() # close
return(my_data) # return
# Check table_names
def get_table_names():
conn, cur = get_conn_cur() # get connection and cursor
# query to get table names
table_name_query = """SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public' """
cur.execute(table_name_query) # execute
my_data = cur.fetchall() # fetch results
cur.close() #close cursor
conn.close() # close connection
return(my_data) # return your fetched results
# make sql_head function
def sql_head(table_name):
conn, cur = get_conn_cur() # get connection and cursor
# Now select column names while inserting the table name into the WERE
head_query = """SELECT * FROM %s LIMIT 5; """ %table_name
cur.execute(head_query) # exectue
colnames = [desc[0] for desc in cur.description] # get column names
my_data = cur.fetchall() # store first five rows
cur.close() # close
conn.close() # close
df = pd.DataFrame(data = my_data, columns = colnames) # make into df
return(df) # return
In the first section there's a small dataset that you can import on the incomes of people that are either in school, working, or retired. Write a groupby statement that returns the average income of each group as well as the min and max incomes within the group. Python code please ASAP!
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
