# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/Bidbalt_TaxSale_Taxlien.ipynb (unless otherwise specified).

__all__ = ['taxlien']

# Cell
def taxlien(df, totalres, year):
  taxlien = df.copy()
  # Aggregate Numeric Values by Sum
  taxlien['taxlienCount'] = 1
  taxlien = taxlien.groupby('CSA2010').sum(numeric_only=True)

  # Make sure ALL csas and BaltimoreCity are included. among other things
  taxlien = totalres[ ['CSA2010','totalres'+year] ].merge( taxlien, left_on='CSA2010', right_on='CSA2010', how='outer' )

  # Update the baltimore CSA.
  taxlien.at[55,'taxlienCount'] = taxlien['taxlienCount'].sum()

  # Create the Indicator
  taxlien['40-taxlien'+year] = taxlien['taxlienCount'] / totalres['totalres'+year] * 100

  taxlien = taxlien[['CSA2010', 'taxlienCount', '40-taxlien'+year, 'totalres'+year ]]

  compareYears = gpd.read_file("https://services1.arcgis.com/mVFRs7NF4iFitgbY/ArcGIS/rest/services/Taxlien/FeatureServer/0/query?where=1%3D1&outFields=*&returnGeometry=true&f=pgeojson");
  prevYear = 'taxlien'+ str( int(year) - 1 )
  if prevYear in compareYears.columns:
    taxlien = taxlien.merge( compareYears[['CSA2010', prevYear]], left_on='CSA2010', right_on='CSA2010', how='outer' )
    taxlien['change'] = taxlien['40-taxlien'+year] - taxlien[ prevYear ]
    taxlien['percentChange'] = taxlien['change'] / taxlien[ prevYear ] * 100
    taxlien['change'] = taxlien['change'].apply(lambda x: "{:.2f}".format(x) )
    taxlien = taxlien[['CSA2010', 'taxlienCount', 'totalres19', 'taxlien18', '40-taxlien19', 'percentChange', 'change']]

  return taxlien