我想在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)
答案 0 :(得分:4)
替代方式
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
答案 1 :(得分:3)
IIUC你希望factorize你的价值观:
dataset[var] = pd.factorize(dataset[var])[0] + 1
演示:
In [2]: df
Out[2]:
col
0 aaa
1 aaa
2 bbb
3 ccc
4 ddd
5 bbb
In [3]: df['col'] = pd.factorize(df['col'])[0] + 1
In [4]: df
Out[4]:
col
0 1
1 1
2 2
3 3
4 4
5 2