roq*_*qds 4 python pandas categorical-data
我有一个关于数千个城市的学校数据的数据框。学校是行标识符,城市编码如下:
school city category capacity
1 azez6576sebd 45 23
2 dsqozbc765aj 12 236
3 sqdqsd12887s 8 63
4 azez6576sebd 7 234
...
Run Code Online (Sandbox Code Playgroud)
我知道有几千个城市,如何将city变量转换为数字?我猜单行编码不合适,因为我的列太多了。将具有数千个级别的分类变量转换为数字的一般方法是什么?
谢谢。
您可以在sklearn中使用category dtype,它应该是 labelencoder
df.city=df.city.astype('category').cat.codes
df
Out[385]:
school city category capacity
0 1 0 45 23
1 2 1 12 236
2 3 2 8 63
3 4 0 7 234
Run Code Online (Sandbox Code Playgroud)
在机器学习分类器的上下文中,几千列仍然是可以管理的。尽管您需要提防维度的诅咒。
除此之外,您不希望get_dummies调用导致内存溢出,因此您可以生成SparseDataFrame-
v = pd.get_dummies(df.set_index('school').city, sparse=True)
v
azez6576sebd dsqozbc765aj sqdqsd12887s
school
1 1 0 0
2 0 1 0
3 0 0 1
4 1 0 0
type(v)
pandas.core.sparse.frame.SparseDataFrame
Run Code Online (Sandbox Code Playgroud)
sdf.to_coo您可以使用-生成稀疏矩阵
v.to_coo()
<4x3 sparse matrix of type '<class 'numpy.uint8'>'
with 4 stored elements in COOrdinate format>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3494 次 |
| 最近记录: |