pandas将文本特征转换为数值

Don*_*the 6 python pandas

我可以通过使用df.astype()方法转换为'category'来转换pandas数据框中的所有文本功能,如下所示.但是我觉得类别难以使用(例如用于绘制数据),并且更愿意创建一个新的整数列

#convert all objects to categories
object_types = dataset.select_dtypes(include=['O'])
for col in object_types:
    dataset['{0}_category'.format(col)] = dataset[col].astype('category')
Run Code Online (Sandbox Code Playgroud)

我可以使用这个hack将文本转换为整数:

#convert all objects to int values
object_types = dataset.select_dtypes(include=['O'])

new_cols = {}
for col in object_types:
    data_set = set(dataset[col].tolist())
    data_indexed = {}
    for i, item in enumerate(data_set):
        data_indexed[item] = i
    new_list = []
    for item in dataset[col].tolist():
        new_list.append(data_indexed[item])
    new_cols[col]=new_list

for key, val in new_cols.items():
    dataset['{0}_int_value'.format(key)] = val
Run Code Online (Sandbox Code Playgroud)

但是有更好的(或现有的)方法吗?

Max*_*axU 7

我会使用factorize方法,它是为这个特定的任务而设计的:

In [90]: x
Out[90]:
    A  B
9   c  z
10  c  z
4   b  x
5   b  y
1   a  w
7   b  z

In [91]: x.apply(lambda col: pd.factorize(col, sort=True)[0])
Out[91]:
    A  B
9   2  3
10  2  3
4   1  1
5   1  2
1   0  0
7   1  3
Run Code Online (Sandbox Code Playgroud)

要么:

In [92]: x.apply(lambda col: pd.factorize(col)[0])
Out[92]:
    A  B
9   0  0
10  0  0
4   1  1
5   1  2
1   2  3
7   1  0
Run Code Online (Sandbox Code Playgroud)