我可以通过使用 df.astype() 方法转换为“类别”来转换 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')
我可以使用这个 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
但是是否有更好的(或现有的)方法来做同样的事情?
最佳答案
我会使用 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
或:
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
关于python - pandas 将文本特征转换为数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40435350/