<jupyter_start><jupyter_text>Exercise 5.02: Creating Features for customer revenue prediction<jupyter_code>import pandas as pd
df = pd.read_csv('azra_retail_transactions.csv')
df.head()
df['InvoiceDate'] = pd.to_datetime(df['InvoiceDate'])
df['revenue'] = df['UnitPrice']*df['Quantity']
df.head()
operations = {'revenue':'sum',
              'InvoiceDate':'first',
              'CustomerID':'first' 
             }
df = df.groupby('InvoiceNo').agg(operations)
df.head()
df['year'] = df['InvoiceDate'].apply(lambda x: x.year)
df['days_since'] = (pd.datetime(year=2019, month=12, day=31) - 
                    df['InvoiceDate']).apply(lambda x: x.days)
operations = {'revenue':'sum',
              'days_since':['max','min','nunique'],
             }

X = df[df['year'] == 2019].groupby('CustomerID').agg(operations)

X.head()
X.columns = [' '.join(col).strip() for col in X.columns.values]
X.head()
X['avg_order_cost'] = X['revenue sum']/X['days_since nunique']
y = df[df['year'] == 2020].groupby('CustomerID')['revenue'].sum()
wrangled_df = pd.concat([X,y], axis=1)
wrangled_df.columns = ['revenue_2019',
                       'days_since_first_purchase',
                       'days_since_last_purchase',
                       'number_of_purchases',
                       'avg_order_cost',
                       'revenue_2020']

wrangled_df.head()
wrangled_df = wrangled_df[~wrangled_df.revenue_2019.isnull()]
wrangled_df = wrangled_df[~wrangled_df.revenue_2020.isnull()]
wrangled_df = wrangled_df[wrangled_df.revenue_2020 < ((wrangled_df.revenue_2020.median()) + wrangled_df.revenue_2020.std()*3)]
wrangled_df = wrangled_df[wrangled_df.revenue_2019 < ((wrangled_df.revenue_2019.median()) + wrangled_df.revenue_2019.std()*3)]
wrangled_df.to_csv('wrangled_transactions.csv')
wrangled_df.head()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17103825136612022, 'fraction_numerical': 0.033879781420765025, 'mean_word_length': 4.002732240437158, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '574948', 'license': 'MIT', 'n_tokens_mistral': 697, 'n_tokens_neox': 635, 'n_words': 83, 'path': 'Chapter05/Exercise 5.02.ipynb', 'repo_name': 'sespezua/Data-Science-for-Marketing-Analytics-Second-Edition', 'size': '1830'}