如何有效编码下表?
例如
is_invocable_r_v
到
import pandas as pd
df = pd.DataFrame(np.array([[1, 2, 3], [2, 3, 4], [1, 3, 4]]), columns=['col_1', 'col_2', 'col_3'])
col_1 col_2 col_3
0 1 2 3
1 2 3 4
2 1 3 4
答案 0 :(得分:1)
这是一种方法-
data_field
使用def hotencode(df):
unq, idx = np.unique(df, return_inverse=1)
col_idx = idx.reshape(df.shape)
out = np.zeros((len(col_idx),col_idx.max()+1),dtype=int)
out[np.arange(len(col_idx))[:,None], col_idx] = 1
return pd.DataFrame(out, columns=unq, index=df.index)
的另一种方法是-
broadcasting
样品运行-
unq = np.unique(df)
out = (df.values[...,None] == unq).any(1).astype(int)