我想对 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)
最佳答案
替代方式
df.col.astype('category').cat.codes.add(1)
Out[697]:
0 1
1 1
2 2
3 3
4 4
5 2
dtype: int8
最好使用 MaxU 的答案:)
%timeit df.col.astype('category').cat.codes.add(1)#Wen
1000 loops, best of 3: 437 µs per loop
%timeit df['col'] = pd.factorize(df['col'])[0] + 1#MaxU
1000 loops, best of 3: 194 µs per loop
关于python - 重新编码 pandas 列的最有效和 pythonic 方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46163849/