简体   繁体   English

将行类别转换为列

[英]Convert Rows Category into Columns

I have an array of categories as follow.我有一系列类别如下。

mappingCategory = ["Animal", "Plant", "Animal", "Human", "Plant"]
Index指数 Category类别
0 0 Animal动物
1 1个 Plant植物
2 2个 Animal动物
3 3个 Human人类
4 4个 Plant植物

I want to convert the array into 2D array where the column is unique category (order by alphabet) and the rows show what category is in that row like this.我想将数组转换为二维数组,其中列是唯一类别(按字母顺序排列),行显示该行中的类别,如下所示。

mappingCategory = [[1, 0, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 0, 1]]
Index指数 Animal动物 Human人类 Plant植物
0 0 1 1个 0 0 0 0
1 1个 0 0 0 0 1 1个
2 2个 1 1个 0 0 0 0
3 3个 0 0 1 1个 0 0
4 4个 0 0 0 0 1 1个

I can build my own function to convert it, but is there any python build in function I could use?我可以构建自己的 function 来转换它,但是我可以使用 function 中的任何 python 构建吗?

You can use .str.get_dummies() , as follows:您可以使用.str.get_dummies() ,如下所示:

If you have a dataframe column named Category , use:如果您有一个名为Category的 dataframe 列,请使用:

df['Category'].str.get_dummies()

Or, if you do it directly from the array of categories:或者,如果您直接从类别数组中执行此操作:

mappingCategory = ["Animal", "Plant", "Animal", "Human", "Plant"]

pd.Series(mappingCategory).str.get_dummies()

Output: Output:

   Animal  Human  Plant
0       1      0      0
1       0      0      1
2       1      0      0
3       0      1      0
4       0      0      1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM