# Buggy code
def cast_df_columns_types(df, stats):
    types_map = {
        DATA_TYPES.NUMERIC: {
            DATA_SUBTYPES.INT: "int64",
            DATA_SUBTYPES.FLOAT: "float64",
            DATA_SUBTYPES.BINARY: "bool",
        },
        DATA_TYPES.DATE: {
            DATA_SUBTYPES.DATE: "datetime64",  # YYYY-MM-DD
            DATA_SUBTYPES.TIMESTAMP: "datetime64",  # YYYY-MM-DD hh:mm:ss or 1852362464
        },
        DATA_TYPES.CATEGORICAL: {
            DATA_SUBTYPES.SINGLE: "category",
            DATA_SUBTYPES.MULTIPLE: "category",
        },
        DATA_TYPES.FILE_PATH: {
            DATA_SUBTYPES.IMAGE: "object",
            DATA_SUBTYPES.VIDEO: "object",
            DATA_SUBTYPES.AUDIO: "object",
        },
        DATA_TYPES.SEQUENTIAL: {DATA_SUBTYPES.ARRAY: "object"},
        DATA_TYPES.TEXT: {DATA_SUBTYPES.SHORT: "object", DATA_SUBTYPES.RICH: "object"},
    }

    columns = [dict(name=x) for x in list(df.keys())]

    for column in columns:
        try:
            name = column["name"]
            col_type = stats[name]["typing"]["data_type"]
            col_subtype = stats[name]["typing"]["data_subtype"]
            new_type = types_map[col_type][col_subtype]
            if new_type == "int64" or new_type == "float64":
                df[name] = df[name].apply(
                    lambda x: x.replace(",", ".") if isinstance(x, str) else x
                )
            if new_type == "int64":
                df = df.astype({name: "float64"})
            df = df.astype({name: new_type})
        except Exception as e:
            print(e)
            print(f"Error: cant convert type of DS column {name} to {new_type}")

    return df


# Traceback (UnboundLocalError)
Traceback (most recent call last):
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/flask_restx/api.py", line 375, in wrapper
resp = resource(*args, **kwargs)
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/flask/views.py", line 89, in view
return self.dispatch_request(*args, **kwargs)
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/flask_restx/resource.py", line 44, in dispatch_request
resp = meth(*args, **kwargs)
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/flask_restx/marshalling.py", line 248, in wrapper
resp = f(*args, **kwargs)
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/mindsdb/api/http/namespaces/datasource.py", line 113, in put
ca.default_store.save_datasource(name, source_type, request.json)
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/mindsdb/interfaces/datastore/datastore.py", line 185, in save_datasource
df_with_types = cast_df_columns_types(df, self.get_analysis(df)['data_analysis_v2'])
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/mindsdb/interfaces/datastore/sqlite_helpers.py", line 54, in cast_df_columns_types
print(f'Error: cant convert type of DS column {name} to {new_type}')
UnboundLocalError: local variable 'new_type' referenced before assignment
ERROR:mindsdb.api.http.initialize:Exception on /api/datasources/AirplaneData [PUT]
Traceback (most recent call last):
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/mindsdb/interfaces/datastore/sqlite_helpers.py", line 44, in cast_df_columns_types
col_type = stats[name]['typing']['data_type']
KeyError: 'typing'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/flask_restx/api.py", line 375, in wrapper
resp = resource(*args, **kwargs)
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/flask/views.py", line 89, in view
return self.dispatch_request(*args, **kwargs)
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/flask_restx/resource.py", line 44, in dispatch_request
resp = meth(*args, **kwargs)
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/flask_restx/marshalling.py", line 248, in wrapper
resp = f(*args, **kwargs)
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/mindsdb/api/http/namespaces/datasource.py", line 113, in put
ca.default_store.save_datasource(name, source_type, request.json)
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/mindsdb/interfaces/datastore/datastore.py", line 185, in save_datasource
df_with_types = cast_df_columns_types(df, self.get_analysis(df)['data_analysis_v2'])
File "/home/zoran/MyProjects/mindsdb-examples/mdb/lib/python3.7/site-packages/mindsdb/interfaces/datastore/sqlite_helpers.py", line 54, in cast_df_columns_types
print(f'Error: cant convert type of DS column {name} to {new_type}')
UnboundLocalError: local variable 'new_type' referenced before assignment

# Fixed code
def cast_df_columns_types(df, stats):
    types_map = {
        DATA_TYPES.NUMERIC: {
            DATA_SUBTYPES.INT: "int64",
            DATA_SUBTYPES.FLOAT: "float64",
            DATA_SUBTYPES.BINARY: "bool",
        },
        DATA_TYPES.DATE: {
            DATA_SUBTYPES.DATE: "datetime64",  # YYYY-MM-DD
            DATA_SUBTYPES.TIMESTAMP: "datetime64",  # YYYY-MM-DD hh:mm:ss or 1852362464
        },
        DATA_TYPES.CATEGORICAL: {
            DATA_SUBTYPES.SINGLE: "category",
            DATA_SUBTYPES.MULTIPLE: "category",
        },
        DATA_TYPES.FILE_PATH: {
            DATA_SUBTYPES.IMAGE: "object",
            DATA_SUBTYPES.VIDEO: "object",
            DATA_SUBTYPES.AUDIO: "object",
        },
        DATA_TYPES.SEQUENTIAL: {DATA_SUBTYPES.ARRAY: "object"},
        DATA_TYPES.TEXT: {DATA_SUBTYPES.SHORT: "object", DATA_SUBTYPES.RICH: "object"},
    }

    columns = [dict(name=x) for x in list(df.keys())]

    for column in columns:
        try:
            name = column["name"]
            if stats[name].get("empty", {}).get("is_empty", False):
                new_type = types_map[DATA_TYPES.NUMERIC][DATA_SUBTYPES.INT]
            else:
                col_type = stats[name]["typing"]["data_type"]
                col_subtype = stats[name]["typing"]["data_subtype"]
                new_type = types_map[col_type][col_subtype]
            if new_type == "int64" or new_type == "float64":
                df[name] = df[name].apply(
                    lambda x: x.replace(",", ".") if isinstance(x, str) else x
                )
            if new_type == "int64":
                df = df.astype({name: "float64"})
            df = df.astype({name: new_type})
        except Exception as e:
            print(e)
            print(f"Error: cant convert type of DS column {name} to {new_type}")

    return df