我想在 pandas DataFrame 中“匿名化”或“重新编码”一列。最有效的方法是什么?我写了以下内容,但似乎有内置函数或更好的方法。
dataset = dataset.sample(frac=1).reset_index(drop=False) # reorders dataframe randomly (helps anonymization, since order could have some meaning)
# make dictionary of old and new values
value_replacer = 1
values_dict = {}
for unique_val in dataset[var].unique():
values_dict[unique_val] = value_replacer
value_replacer += 1
# replace old values with new
for k, v in values_dict.items():
dataset[var].replace(to_replace=k, value=v, inplace=True)