chech if the below methods
nonLocalBrokerMapCREATE(nonLocalMapFile="nonLocalBrokersToEIN")
localBrokerRevertMapCREATE
Create_Broker_Comm_Fee()
are present in
-- coding: utf-8 --
"""
Created on Tue May 2 14:15:28 2023
@author: akovvuri
"""
import pandas as pd
import numpy as np
import os
from math import radians, cos, sin, asin, sqrt, atan2
def haversine(lat1, lon1, lat2, lon2):
R = 6378137 # this is in miles. For Earth radius in kilometers use 6372.8 km
code
dLat = radians(lat2 - lat1)
dLon = radians(lon2 - lon1)
lat1 = radians(lat1)
lat2 = radians(lat2)
a = sin(dLat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dLon / 2) ** 2
a = min(a, 1)
c = 2 * asin(sqrt(a))
c = c * R
dist = atan2(sqrt(a), sqrt(1 - a)) * R * 2
# print(c,dist)
return c
haversine_v = np.vectorize(haversine)
print("\nSource brokerLocation.py", dot20)
def nonLocalBrokerMapCREATE(
stdInFileBrok="brokers.all.yrs.Standardized",
nonLocalMapFile="nonLocalBrokersToEIN"
):
if "nonLocalBrokerMap" in globals():
del globals()["nonLocalBrokerMap"]
print("Remove nonLocalBrokerMap and recreate")
code
Assistant
Yes, the functions you mentioned are present in the provided code. Here’s a summary:
nonLocalBrokerMapCREATE(nonLocalMapFile="nonLocalBrokersToEIN"): This function is fully defined and creates a non-local broker map from a standardized broker input file.
localBrokerRevertMapCREATE: This function is also fully defined. It creates a local broker revert map from standardized broker data and an address-to-zipcode mapping.
Create_Broker_Comm_Fee(): This function is not present in the provided code snippet. There are no definitions or mentions of this function within the entire script.
If you need further assistance or a deeper examination of specific parts of the code, feel free to ask!
User
can u please give me the code snippets of these
nonLocalBrokerMapCREATE(nonLocalMapFile="nonLocalBrokersToEIN"): This function is fully defined and creates a non-local broker map from a standardized broker input file.
localBrokerRevertMapCREATE: This function is also fully defined. It creates a local broker revert map from standardized broker data and an address-to-zipcode mapping.
Assistant
User
can u please explain this code to mw with an example
def nonLocalBrokerMapCREATE(
stdInFileBrok="brokers.all.yrs.Standardized",
nonLocalMapFile="nonLocalBrokersToEIN"
):
if "nonLocalBrokerMap" in globals():
del globals()["nonLocalBrokerMap"]
print("Remove nonLocalBrokerMap and recreate")
code
Assistant
all = pd.read_pickle(os.path.join(dataDir, "brokers", stdInFileBrok + ".pkl"))
all["BROKER_ZIPCODE"] = np.where(
(all.BROKER_ZIPCODE != "") & (all.BROKER_ZIPCODE != "0"),
all.BROKER_ZIPCODE.astype(str).str.split(".").str[0].str.zfill(5),
all["BROKER_ZIPCODE"],
)
all["Zipcode"] = np.where(
(all.Zipcode != "") & (all.Zipcode != "0"),
all.Zipcode.astype(str).str.split(".").str[0].str.zfill(5),
all["Zipcode"],
)
all = all[(all["BROKER_STATE"] != "") & (all["State_HQ"] != "")]
all = addBrokerLocationAdjustmentFields(dt=all.copy())
all["LocCt"] = all.groupby(["State_HQ", "EIN", "BROKER"])["NonLoc"].transform(
lambda x: sum(1 - x)
)
dt = all[all["NonLoc"] == 1]
obs = len(dt)
begVars = dt.columns
print("\nNonLoc obs on initial dataset ", len(dt), "out of", len(all))
rule = "\n \n1.If the broker X group is sometimes local, assume it is actualy local (just entered HQ)"
dt["NonLocCt"] = dt.groupby(["State_HQ", "EIN", "BROKER"])["Members"].transform(
"count"
)
dt["LOCAL"] = np.where((dt["PlaysInHQ"] == 1) & (dt["LocCt"] > 0), 1, 0)
print(rule, dt["LOCAL"].sum(), "out of", len(dt))
dt = dt[dt["LOCAL"] == 0]
print(" remaining possible non-locals ", len(dt))
dt[dt.BROKER_ZIPCODE == "04101"].BROKER.value_counts(dropna=False)
dt["BROKER_ZIPCODE"] = dt["BROKER_ZIPCODE"].astype(str)
dt["BROKER_ZIPCODE"] = np.where(
(dt.BROKER_ZIPCODE != "") & (dt.BROKER_ZIPCODE != "0"),
dt.BROKER_ZIPCODE.astype(str).str.split(".").str[0].str.zfill(5),
dt.BROKER_ZIPCODE,
)
# dt['BROKER_ZIPCODE']=dt['BROKER_ZIPCODE'].astype(str).str.split(".").str[0].str.zfill(5)
dt["BROKER_HQ_ZIP"] = np.where(
dt["BROKER_HQ_ZIP"] != "",
dt["BROKER_HQ_ZIP"].astype(str).str.split(".").str[0].str.zfill(5),
dt["BROKER_HQ_ZIP"],
)
dt["BROKER_HQ_ZIP2"] = np.where(
dt["BROKER_HQ_ZIP2"] != "",
dt["BROKER_HQ_ZIP2"].astype(str).str.split(".").str[0].str.zfill(5),
dt["BROKER_HQ_ZIP2"],
)
dt[(dt["BROKER_ZIPCODE"] == dt["BROKER_HQ_ZIP2"])].BROKER_HQ_ZIP2.value_counts(
dropna=False
)
rule = "\n \n2.If the broker DOES play in the group's HQ state & they entered the broker's HQ assume local"
dt["LOCAL"] = np.where(
(dt["PlaysInHQ"] == 1)
& (
(dt["BROKER_ZIPCODE"] == dt["BROKER_HQ_ZIP"])
| (dt["BROKER_ZIPCODE"] == dt["BROKER_HQ_ZIP2"])
),
1,
0,
)
print(rule, dt["LOCAL"].sum(), "out of", len(dt))
dt = dt[dt["LOCAL"] == 0]
print(" remaining ", len(dt))
rule = "\nAssume the rest are non-local "
dt = dt[
["State_HQ", "EIN", "BROKER", "BROKER_STATE", "BROKER_ZIPCODE"]
].drop_duplicates()
dt.to_pickle(os.path.join(dataDir, "brokers", nonLocalMapFile + ".pkl"))
print(
"\nObs saved in",
nonLocalMapFile,
"in dataDir/brokers ",
len(dt),
" non-local broker to group pairs",
)
globals()["nonLocalBrokerMap"] = dt.copy()
print(" saved to global Envt as nonLocalBrokerMap")
def localBrokerRevertMapCREATE(
addressMapFile="BrokerAddressZipcodeMap",
stdInFileBrok="brokers.all.yrs.Standardized",
localRevertMapFile="localBrokerReversionMap",
):
if "revertToLocalMap" in globals():
del globals()["revertToLocalMap"]
print("Remove revertToLocalMap and recreate")
code
all = pd.read_pickle(os.path.join(dataDir, "brokers", stdInFileBrok + ".pkl"))
all = all[
(all["BROKER_STATE"] != "")
& (all["State_HQ"] != "")
& (~all["BROKER"].isin(badBrokTerms))
]
all["BROKER_ZIPCODE"] = np.where(
(all.BROKER_ZIPCODE != "") & (all.BROKER_ZIPCODE != "0"),
all.BROKER_ZIPCODE.astype(str).str.split(".").str[0].str.zfill(5),
all["BROKER_ZIPCODE"],
)
all["Zipcode"] = np.where(
(all.Zipcode != "") & (all.Zipcode != "0"),
all.Zipcode.astype(str).str.split(".").str[0].str.zfill(5),
all["Zipcode"],
)
all = addBrokerLocationAdjustmentFields(dt=all.copy())
print(
"\n\nStart localBrokerRevertMapCREATE NonLoc ",
all["NonLoc"].mean(),
" out of ",
len(all),
)
# all.columns
# addMap[addMap.EIN==460743136]['BROKER_ADDRESS']
print(" pct of obs OnNonLocMap ", round(100 * all["OnNonLocMap"].mean()))
all["BROKER_ZIPCODE"] = (
all["BROKER_ZIPCODE"].astype(str).str.split(".").str[0].str.zfill(5)
)
dt = all[(all["OnNonLocMap"] == 0) & (all["NonLoc"] == 1) & (all["Zipcode"] != "")][
["State_HQ", "EIN", "Zipcode", "BROKER", "BROKER_STATE", "BROKER_ZIPCODE"]
].drop_duplicates()
print(
"\nUnique obs we need to revert ", len(dt), " out of initial on all ", len(all)
)
dt = dt.drop(["BROKER_STATE", "BROKER_ZIPCODE"], axis=1)
dt["KEY"] = dt["BROKER"] + dt["State_HQ"]
addMap = pd.read_pickle(os.path.join(brokerDir, addressMapFile + ".pkl"))
addMap["KEY"] = addMap["BROKER_NAME"] + addMap["BROKER_STATE"]
addMap["OnRevert"] = np.where(addMap["KEY"].isin(dt["KEY"]), 1, 0)
print("\naddMap to keep ", addMap["OnRevert"].sum(), "out of ", len(addMap))
addMap = addMap[addMap["OnRevert"] == 1]
print("\nObs in addMap on the revert dt.", len(addMap))
rule = "\n1.If a single-office-by-state broker use that info "
single = addMap[["BROKER_NAME", "BROKER_STATE", "BROKER_ZIPCODE"]].drop_duplicates()
single["CT"] = single.groupby(["BROKER_NAME", "BROKER_STATE"])[
"BROKER_ZIPCODE"
].transform("count")
single = single[single["CT"] == 1]
single = single.drop("CT", axis=1)
print("\nObs in single ", len(single), " and vars ", single.columns)
dt.isnull().sum()
dt = pd.merge(
dt,
single,
left_on=["BROKER", "State_HQ"],
right_on=["BROKER_NAME", "BROKER_STATE"],
how="left",
)
dt = dt.drop(["BROKER_NAME", "BROKER_STATE"], axis=1)
for v in ["BROKER_ZIPCODE"]:
dt[v] = dt[v].fillna("")
revert2 = dt[dt["BROKER_ZIPCODE"] != ""].drop_duplicates()
print("\nSingle-office obs to update ", len(revert2), "out of ", len(dt))
na = revert2.columns[revert2.isna().any()].tolist()
if len(na) > 0:
raise Exception(na + " - NAs in revert2")
dt = cleanupJunk(dt=dt)
dt = dt[dt["BROKER_ZIPCODE"] == ""].drop_duplicates()
print(" and obs remaining to revert in dt ", len(dt))
rule = "\n3.If the exact ZIP_HQ (Zipcode) and State_HQ are associated with the broker use them"
addMap["CT"] = addMap.groupby(["BROKER_NAME", "BROKER_STATE"])[
"BROKER_ZIPCODE"
].transform("count")
addMap = addMap[addMap["CT"] > 1]
print("\nObs in map remaining with 2+ offices per state ", len(addMap))
dt["KEY"] = dt["BROKER"] + dt["State_HQ"] + dt["Zipcode"].astype(str)
addMap["KEY"] = (
addMap["BROKER_NAME"] + addMap["BROKER_STATE"] + addMap["BROKER_ZIPCODE"]
)
revert3 = dt[dt["KEY"].isin(addMap["KEY"])].drop_duplicates()
print(rule, " in revert3 ", len(revert3))
revert3["BROKER_ZIPCODE"] = revert3["Zipcode"]
te = revert3.drop_duplicates()
if len(te) != len(revert3):
raise Exception("\nNon-uq obs in revert3 ", len(revert) - len(te))
na = revert3.columns[revert3.isna().any()].tolist()
if len(na) > 0:
raise Exception(str(na) + " - NAs in revert3")
dt = dt[~dt["KEY"].isin(addMap["KEY"])].drop_duplicates()
print(" and remaining to revert ", len(dt))
rule = "\n4.Nearest distance "
zipMap = pd.DataFrame(zipcode_to_lat_lng)
zipMap = zipMap.drop("ZIP", axis=1)
dt["Zipcode"] = dt["Zipcode"].astype(str)
zipMap.ZIPCODE = zipMap.ZIPCODE.astype(str).str.zfill(5)
dt["Zipcode"] = dt["Zipcode"].astype(str)
dt = pd.merge(dt, zipMap, left_on="Zipcode", right_on="ZIPCODE", how="left")
dt["LAT"] = dt["LAT"].fillna(0)
dt["LNG"] = dt["LNG"].fillna(0)
dt = dt.rename(columns={"LAT": "LAT_HQ", "LNG": "LNG_HQ"})
addMap = pd.merge(
addMap, zipMap, left_on="BROKER_ZIPCODE", right_on="ZIPCODE", how="left"
)
addMap = addMap.drop(["ZIPCODE"], axis=1)
addMap["LAT"] = addMap["LAT"].fillna(0)
addMap["LNG"] = addMap["LNG"].fillna(0)
dtZips = dt[["Zipcode", "LAT_HQ", "LNG_HQ", "State_HQ", "BROKER"]].drop_duplicates()
mapZips = addMap[
["BROKER_ZIPCODE", "LAT", "LNG", "BROKER_STATE", "BROKER_NAME"]
].drop_duplicates()
brokZips = pd.merge(
dtZips,
mapZips,
left_on=["BROKER", "State_HQ"],
right_on=["BROKER_NAME", "BROKER_STATE"],
)
brokZips = brokZips.drop(["BROKER_NAME", "BROKER_STATE"], axis=1)
na = brokZips.columns[brokZips.isna().any()].tolist()
if len(na) > 0:
raise Exception(na + " - NAs in brokZips @145")
print(
"\nObs in brokZips ",
len(brokZips),
"from obs in dtZips ",
len(dtZips),
" and mapZips ",
len(mapZips),
)
# brokZips["dist"] = haversine(brokZips[["LNG_HQ", "LAT_HQ"]], brokZips[["LNG", "LAT"]])
brokZips["dist"] = haversine_v(
brokZips["LAT_HQ"], brokZips["LNG_HQ"], brokZips["LAT"], brokZips["LNG"]
)
brokZips = brokZips.sort_values(["BROKER", "Zipcode", "dist"])
brokZips["IND"] = brokZips.groupby(["BROKER", "State_HQ", "Zipcode"]).cumcount() + 1
brokZips = brokZips[brokZips["IND"] == 1][
["BROKER", "State_HQ", "Zipcode", "BROKER_ZIPCODE"]
]
try:
dt = dt.drop(["Unnamed: 0"], axis=1)
except:
print("no unnamed")
dt = dt.drop(["ZIPCODE"], axis=1)
na = dt.columns[dt.isna().any()].tolist()
if len(na) > 0:
raise Exception(na + " - NAs in dt @145")
sub = dt.copy()
sub = sub.drop("BROKER_ZIPCODE", axis=1)
revert4 = pd.merge(sub, brokZips, on=["BROKER", "State_HQ", "Zipcode"], how="left")
revert4["BROKER_ZIPCODE"] = revert4["BROKER_ZIPCODE"].fillna(revert4["Zipcode"])
te = revert4[revert4["BROKER_ZIPCODE"] == ""]
print("\nrevert4 miss broker zip ", len(te), " of", len(revert4))
na = revert4.columns[revert4.isna().any()].tolist()
if len(na) > 0:
raise Exception(na + " - NAs in revert4")
print(rule, " obs saved in revert4 ", len(revert4))
revert2 = cleanupJunk(dt=revert2)
revert3 = cleanupJunk(dt=revert3)
revert4 = cleanupJunk(dt=revert4)
te = revert2.drop_duplicates()
if len(te) != len(revert2):
raise Exception("\nNon-unique obs in revert2 ", len(revert2) - len(te))
revert2["RevertMethod"] = "revert2"
revert3["RevertMethod"] = "revert3"
revert4["RevertMethod"] = "revert4"
vars = ["State_HQ", "EIN", "Zipcode", "BROKER", "BROKER_ZIPCODE", "RevertMethod"]
all = pd.concat([revert2[vars], revert3[vars], revert4[vars]])
map = pd.read_pickle(brokerDir + "BrokerAddressZipcodeMap.pkl")
map = map[
["BROKER_NAME", "BROKER_ZIPCODE", "BROKER_ADDRESS", "Groups", "GroupsXBrokXSt"]
]
map = map.sort_values(
["BROKER_NAME", "BROKER_ZIPCODE", "Groups"], ascending=[True, True, False]
)
map["IND"] = map.groupby(["BROKER_NAME", "BROKER_ZIPCODE"]).cumcount() + 1
map = map[map["IND"] == 1]
map = map.drop(["IND", "Groups"], axis=1)
all.BROKER_ZIPCODE.str.len().value_counts(dropna=False)
all["BROKER_ZIPCODE"] = all["BROKER_ZIPCODE"].astype(str).str.zfill(5)
all = pd.merge(
all,
map,
left_on=["BROKER", "BROKER_ZIPCODE"],
right_on=["BROKER_NAME", "BROKER_ZIPCODE"],
how="left",
)
all["BROKER_ADDRESS"] = all["BROKER_ADDRESS"].fillna("")
try:
all = all.drop("KEY", axis=1)
except:
print("key np")
print(
"\nObs to save on",
localRevertMapFile,
" ",
len(all),
" and var names ",
all.columns,
)
all.to_pickle(os.path.join(dataDir, "brokers", localRevertMapFile + ".pkl"))
globals()["revertToLocalMap"] = all.copy()
print(
"\nSaved in",
localRevertMapFile,
" in dataDir/brokers ",
len(all),
"in Global as revertToLocaMap",
)
Certainly! Here are the code snippets for the functions nonLocalBrokerMapCREATE and localBrokerRevertMapCREATE as defined in your provided code:
1. nonLocalBrokerMapCREATE
This function creates a non-local broker map based on standardized broker data.
python
def nonLocalBrokerMapCREATE(
stdInFileBrok="brokers.all.yrs.Standardized",
nonLocalMapFile="nonLocalBrokersToEIN"
):
if "nonLocalBrokerMap" in globals():
del globals()["nonLocalBrokerMap"]
print("Remove nonLocalBrokerMap and recreate")
all = pd.read_pickle(os.path.join(dataDir, "brokers", stdInFileBrok + ".pkl"))
# Normalize ZIP codes
all["BROKER_ZIPCODE"] = np.where(
(all.BROKER_ZIPCODE != "") & (all.BROKER_ZIPCODE != "0"),
all.BROKER_ZIPCODE.astype(str).str.split(".").str[0].str.zfill(5),
all["BROKER_ZIPCODE"],
)
all["Zipcode"] = np.where(
(all.Zipcode != "") & (all.Zipcode != "0"),
all.Zipcode.astype(str).str.split(".").str[0].str.zfill(5),
all["Zipcode"],
)
all = all[(all["BROKER_STATE"] != "") & (all["State_HQ"] != "")]
all = addBrokerLocationAdjustmentFields(dt=all.copy())
all["LocCt"] = all.groupby(["State_HQ", "EIN", "BROKER"])["NonLoc"].transform(
lambda x: sum(1 - x)
)
dt = all[all["NonLoc"] == 1]
print("\nNonLoc obs on initial dataset ", len(dt), "out of", len(all))
dt["NonLocCt"] = dt.groupby(["State_HQ", "EIN", "BROKER"])["Members"].transform("count")
dt["LOCAL"] = np.where((dt["PlaysInHQ"] == 1) & (dt["LocCt"] > 0), 1, 0)
dt = dt[dt["LOCAL"] == 0]
print(" remaining possible non-locals ", len(dt))
# Further processing and rules...
dt = dt[["State_HQ", "EIN", "BROKER", "BROKER_STATE", "BROKER_ZIPCODE"]].drop_duplicates()
dt.to_pickle(os.path.join(dataDir, "brokers", nonLocalMapFile + ".pkl"))
globals()["nonLocalBrokerMap"] = dt.copy()
print(" saved to global Envt as nonLocalBrokerMap")
2. localBrokerRevertMapCREATE
This function creates a local broker revert map from standardized broker data and an address-to-zipcode mapping.
python
def localBrokerRevertMapCREATE(
addressMapFile="BrokerAddressZipcodeMap",
stdInFileBrok="brokers.all.yrs.Standardized",
localRevertMapFile="localBrokerReversionMap",
):
if "revertToLocalMap" in globals():
del globals()["revertToLocalMap"]
print("Remove revertToLocalMap and recreate")
all = pd.read_pickle(os.path.join(dataDir, "brokers", stdInFileBrok + ".pkl"))
all = all[
(all["BROKER_STATE"] != "")
& (all["State_HQ"] != "")
& (~all["BROKER"].isin(badBrokTerms))
]
# Normalize ZIP codes
all["BROKER_ZIPCODE"] = np.where(
(all.BROKER_ZIPCODE != "") & (all.BROKER_ZIPCODE != "0"),
all.BROKER_ZIPCODE.astype(str).str.split(".").str[0].str.zfill(5),
all["BROKER_ZIPCODE"],
)
all["Zipcode"] = np.where(
(all.Zipcode != "") & (all.Zipcode != "0"),
all.Zipcode.astype(str).str.split(".").str[0].str.zfill(5),
all["Zipcode"],
)
all = addBrokerLocationAdjustmentFields(dt=all.copy())
dt = all[(all["OnNonLocMap"] == 0) & (all["NonLoc"] == 1) & (all["Zipcode"] != "")][
["State_HQ", "EIN", "Zipcode", "BROKER", "BROKER_STATE", "BROKER_ZIPCODE"]
].drop_duplicates()
dt = dt.drop(["BROKER_STATE", "BROKER_ZIPCODE"], axis=1)
dt["KEY"] = dt["BROKER"] + dt["State_HQ"]
addMap = pd.read_pickle(os.path.join(brokerDir, addressMapFile + ".pkl"))
# Further processing...
all.to_pickle(os.path.join(dataDir, "brokers", localRevertMapFile + ".pkl"))
globals()["revertToLocalMap"] = all.copy()
print(
"\nSaved in",
localRevertMapFile,
" in dataDir/brokers ",
len(all),
"in Global as revertToLocalMap",
)
Explanation:
nonLocalBrokerMapCREATE: This function processes broker data to identify non-local brokers, applying various rules and finally saving the results in a specified file.
localBrokerRevertMapCREATE: This function identifies brokers from non-local mappings that should be reverted to local ones based on certain criteria, processes that data, and saves it.
If you have any further questions or need additional information, feel free to ask!
Certainly! Let's break down the nonLocalBrokerMapCREATE function step by step and explain its purpose, logic, and how it processes data, including an illustrative example.
Purpose of the Function
The nonLocalBrokerMapCREATE function processes broker data to identify which brokers can be classified as "non-local." A non-local broker is one that does not operate primarily in the same state as their Headquarters (HQ).
Function Explanation
Here's a detailed breakdown of the code:
Input Parameters:
stdInFileBrok: The name of the input file that contains standardized broker data.
nonLocalMapFile: The filename for the output data that will contain the non-local brokers.
Remove Previous Global Variable:
python
if "nonLocalBrokerMap" in globals():
del globals()["nonLocalBrokerMap"]
print("Remove nonLocalBrokerMap and recreate")
This checks if nonLocalBrokerMap already exists in the global namespace. If it does, it deletes it to ensure that the function starts with a clean slate.
Load Data:
python
all = pd.read_pickle(os.path.join(dataDir, "brokers", stdInFileBrok + ".pkl"))
This line reads broker data from a pickle file, which presumably contains a DataFrame with various broker attributes, including their ZIP codes and state information.
This code segment normalizes the ZIP codes of brokers by padding them with leading zeros to ensure they are 5 digits. It only processes those ZIP codes that are not empty or zero.
Filter Data:
python
all = all[(all["BROKER_STATE"] != "") & (all["State_HQ"] != "")]
Here, the code filters out any records where either the broker's state or the headquarters state is not provided.
Add Location Adjustment Fields:
python
all = addBrokerLocationAdjustmentFields(dt=all.copy())
This calls another function (presumably defined elsewhere) that modifies the DataFrame, adding additional location-related fields.
This filters the dataset to only include brokers marked as non-local (where the NonLoc flag is set to 1). The length of this filtered dataset is printed.
Here, another count is created to track the number of members associated with each non-local grouping.
The code determines if the brokers are local based on certain conditions (if they play in the HQ state and have other local members).
The result is then filtered to keep only brokers that are confirmed as non-local.
Create Output File:
python
dt = dt[["State_HQ", "EIN", "BROKER", "BROKER_STATE", "BROKER_ZIPCODE"]].drop_duplicates()
dt.to_pickle(os.path.join(dataDir, "brokers", nonLocalMapFile + ".pkl"))
globals()["nonLocalBrokerMap"] = dt.copy()
print(" saved to global Envt as nonLocalBrokerMap")
Finally, it selects specific columns for the final output and saves the filtered DataFrame as a new pickle file. It also makes this DataFrame available globally.
Example Scenario
Let's assume we have the following simplified data in a CSV or pickle file brokers.all.yrs.Standardized.pkl:
BROKER
BROKER_STATE
State_HQ
BROKER_ZIPCODE
NonLoc
PlaysInHQ
EIN
Broker A
CA
CA
90001
0
1
123456789
Broker B
NV
CA
89501
1
0
987654321
Broker C
CA
NV
90210
1
1
123456789
Broker D
TX
CA
73301
0
0
456789123
Normalization: ZIP codes would remain unchanged as they are already 5 digits.
Filtering: Since all entries have valid states, they remain in the DataFrame.
Identifying Non-Local Brokers:
Broker A would not be included as NonLoc = 0.
Broker B (from NV with HQ in CA) would be included as a non-local broker.
Broker C would be excluded because they have a PlaysInHQ = 1.
Broker D would not be included for similar reasons to Broker A.
Final Output: After the filtering process, the remaining rows (mostly non-local brokers) would be saved, and the final DataFrame might look something like this:
State_HQ
EIN
BROKER
BROKER_STATE
BROKER_ZIPCODE
CA
987654321
Broker B
NV
89501
The DataFrame saved as nonLocalBrokersToEIN.pkl would contain Broker B as the only identified non-local broker.
Feel free to ask if you have more questions or need further clarification!