我有一个包含医疗保险信息的pandas DataFrame,包括姓名、地址、出生日期等。
我编写了一个针对单行数据的函数:
def make_hash(partner: str, df: pd.DataFrame) -> str:
"""
For Partner A, df (pd.DataFrame) must contain:
health_plan_id: str
date_of_birth: dt.Timestamp
first_name: str
Other partners will have different feature names for hash input and require a new elif block, below.
"""
if partner == 'Partner A':
health_plan_id = str(df.loc[:,'ID'].item()).strip().encode()
date_of_birth = str(dt.date(df.loc[:,'Date of Birth'].item())).encode()
first_name = str(df.loc[:,'Member Name'].item()).split(",")[1].strip().encode()
hash_input = health_plan_id + date_of_birth + first_name
h = hashlib.sha256(string=hash_input).hexdigest()
print(f"Input: {hash_input}. Result: {h}.\n")
return h
else:
print("No hashing strategy defined for that partner.")
输出结果(PII值已更改):
make_hash(partner="Partner A", df=df)
Input: b'B88845204081984-06-11MickeyMouse'. Result: 4d578e1acd7c670193448b84362095383cc13a24249f6c8c92816d79ec3c48d8.
Out[60]: '4d578e1acd7c670193448b84362095383cc13a24249f6c8c92816d79ec3c48d8'
理想情况下,它应该生成一个新列 (ID
),并将 '4d578e1acd...' 值添加到其中。如果我尝试在具有> 1行的 DataFrame 上使用此函数,则会出现错误:
ValueError: can only convert an array of size 1 to a Python scalar
我希望该函数可以在lambda中使用,能够处理具有任意行数的pd.DataFrame
,并期望输出为另一个pd.DataFrame
,其行数相同,但特征数增加1(新的ID
列)。
这可行吗?我看到了几个类似的问题,但我不确定是否可以在整个pd.Series
上执行此操作,因为上述函数将具有一些依赖于partner
值的数据清理步骤...
.split(",").str[1]
是否完全正确。应该是这样的:.split(",", 1, expand=True)[1]
。 - suvayu