如何解决这个变化的数据框问题

西蒙·林

假设我有一个包含这两列的数据框。

User_id hotel_cluster 
   1     0
   2     2
   3     2
   3     3 
   3     0
   4     2

我想将其更改为此类。我需要编写一个函数还是有熊猫方法?

User_id hotel_cluster_0 hotel_cluster_1 hotel_cluster_2 hotel_cluster_3
  1          1                  0             0              0
  2          0                  0             1              0
  3          1                  0             1              1
  4          0                  0             1              0

请帮忙!抱歉,如果我没有以正确的格式发布问题,谢谢!

海盗

也可以看看


达蒙:

选项1

首先更改'hotel_cluster'包含不存在类别的类别

col = 'hotel_cluster'
df[col] = pd.Categorical(df[col], categories=[0, 1, 2, 3])
pd.crosstab(*map(df.get, df)).add_prefix(f"{col}_")

hotel_cluster  hotel_cluster_0  hotel_cluster_1  hotel_cluster_2  hotel_cluster_3
User_id                                                                          
1                            1                0                0                0
2                            0                0                1                0
3                            1                0                1                1
4                            0                0                1                0

选项2

重新索引后 crosstab

pd.crosstab(*map(df.get, df)).reindex(
    columns=range(4), fill_value=0
).add_prefix('hotel_cluster_')

hotel_cluster  hotel_cluster_0  hotel_cluster_1  hotel_cluster_2  hotel_cluster_3
User_id                                                                          
1                            1                0                0                0
2                            0                0                1                0
3                            1                0                1                1
4                            0                0                1                0

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章