# -------------------------------------------------------------------------------- NOTEBOOK-CELL: CODE
# -*- coding: utf-8 -*-
import dataiku
import pandas as pd, numpy as np
from dataiku import pandasutils as pdu

# Read recipe inputs
top_products_by_topic = dataiku.Dataset("top_products_by_topic")
top_products_by_topic_df = top_products_by_topic.get_dataframe()


top_products_by_topic_df = top_products_by_topic_df.rename(columns={"llm_rating_avg": "2. Topic Rating", "product_id": "1. Product Name", "count": "3. # occurences"})

top_products_by_topic_df["2. Topic Rating"] = top_products_by_topic_df["2. Topic Rating"].apply(lambda rating:np.round(rating,2))

table = pd.pivot(top_products_by_topic_df, values=['1. Product Name', "2. Topic Rating","3. # occurences"], index='rownumber',

                       columns=['topic_name']).swaplevel(axis=1)

table.columns = table.columns.map(' | '.join).str.strip('|')
pivoted_top_products_df = table.reindex(sorted(table.columns), axis=1)


# Write recipe outputs
pivoted_top_products = dataiku.Dataset("pivoted_top_products")
pivoted_top_products.write_with_schema(pivoted_top_products_df)