3 回答
TA贡献1796条经验 获得超4个赞
我复制了您提供的数据,然后计算了距离。对于每个发行人,我找到最近的发行人及其距离。请参阅下面的修改代码。如果您需要更多详细信息,请告诉我。
issuers = ["Ryerson Tull Inc", "Siebel Sys Inc", "Travis Boats & Motors Inc", "Channell Commercial Corp", "Printware Inc",
"AAA", "BBB", "ZZZ"]
ttl_assets = [9322000.0, 995010.0, 313500.0, 426580.0, 145750.0, 299999.0, 399999.0, 123456.0]
long_term_debt = [2632000.0, 0.0, 43340.0, 3380.0, 0.0, 11111.0, 22222.0, 87500.0]
sic_code = [3661, 2456, 3661, 7483, 8473, 3661, 7483, 3661]
ipo_year = [1996, 1996, 1996, 1996, 1996, 1996, 1996, 1997]
data = pd.DataFrame({"issuer": issuers,
"total assets": ttl_assets,
"long term debt": long_term_debt,
"SIC-Code": sic_code,
"IPO Year": ipo_year
})
def get_distance(x1, x2):
""" computes euclidean distance between two points """
d = math.sqrt((x1[0] - x2[0])**2 + (x1[1] - x2[1])**2)
return round(d, 3)
distMatrix = np.ndarray(shape=(len(data), len(data))) # creating an array to fill up the distances
distMatrix[:, :] = np.inf
for i in range(len(data)):
for j in range(len(data)):
if data.loc[i, "SIC-Code"] == data.loc[j, "SIC-Code"] and data.loc[i, "IPO Year"] == data.loc[j, "IPO Year"] and i != j:
issuer1 = data.loc[i, ["total assets", "long term debt"]].values
issuer2 = data.loc[j, ["total assets", "long term debt"]].values
distance = get_distance(issuer1, issuer2)
distMatrix[i, j] = distance
listIssuers = data["issuer"].tolist()
arrMinDist = distMatrix.argmin(axis=0)
dictMinDistIssuer = {} # dictionary that maps each issuer to its closest issuer
dictMinDist = {} # maps each each issuer to the closest issuers distance
dfDist = pd.DataFrame(distMatrix.tolist())
dfDist.columns = listIssuers
dfDist.insert(0, "issuer", listIssuers)
dfDist.insert(1, "IPO Year", ipo_year)
dfDist.insert(2, "SIC-Code", sic_code)
for issuer_idx, min_idx in enumerate(arrMinDist):
distance_value_counts = np.where(distMatrix==np.inf, 0, 1).sum(axis=0) # this checks if there are any matches for each issuer
if distance_value_counts[issuer_idx] == 0:
dictMinDistIssuer[listIssuers[issuer_idx]] = np.nan
dictMinDist[listIssuers[issuer_idx]] = np.nan
else:
dictMinDistIssuer[listIssuers[issuer_idx]] = listIssuers[min_idx]
dictMinDist[listIssuers[issuer_idx]] = distMatrix[issuer_idx][min_idx]
dfDist["closest issuer"] = dfDist["issuer"].map(dictMinDistIssuer)
dfDist["closest issuer dist"] = dfDist["issuer"].map(dictMinDist)
dfDist.replace(to_replace=np.inf, value=np.nan, inplace=True)
TA贡献1815条经验 获得超6个赞
SIC-Code
考虑通过和 lesser对所有可能的配对将数据框与自身进行自连接IPO-Year
。一定要避免反向重复。然后使用Numpy 数学和系列运算跨列运行简单的矢量化算术计算。不需要循环。
TA贡献1824条经验 获得超6个赞
import numpy as np
import pandas as pd
...
# REMOVE SPACES AND HYPHENS IN COLUMNS
df.columns = df.columns.str.replace(r'[ -]', '_')
# SELF JOIN AND AVOID REVERSE DUPLICATES WITH LESSER YEAR
df = (df.merge(df, on=['SIC-Code'])
.query("(Cusip9_x < Cusip9_y) & (Issuer_x < Issuer_y) & (IPO_Year_x < IPO_Year_y)")
)
# SIMILARITY SCORE CALCULATION
df['similarity_score'] = np.sqrt((df['Total_Assets_x'] - df['Total_Assets_y']).pow(2) +
(df['Long_Term_Debt_x'] - df['Long_Term_Debt_y']).pow(2))
添加回答
举报