【问题标题】:Convert dataframe to a numpy matrix将数据框转换为 numpy 矩阵
【发布时间】:2016-12-01 19:01:03
【问题描述】:

我有表单的数据框

user_id  item_id  rating
1          abc       5
1          abcd      3
2          abc       3
2          fgh       5

我想把它转换成一个numpy矩阵比如

# abc  abcd  fgh
[[5,    3,    0]  # user_id 1
[3,    0,    5]] # user_id 2

谁能帮忙?

【问题讨论】:

    标签: python python-3.x pandas numpy dataframe


    【解决方案1】:

    您可以将pivotfillna 一起使用,转换为int,最后通过values 转换为数组:

    arr = df.pivot('user_id', 'item_id', 'rating').fillna(0).astype(int).values
    print (arr)
    [[5 3 0]
     [3 0 5]]
    

    set_indexunstackvalues 的另一种解决方案:

    arr = df.set_index(['user_id','item_id']).unstack(fill_value=0).values
    print (arr)
    [[5 3 0]
     [3 0 5]]
    

    【讨论】:

      猜你喜欢
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-30
      相关资源
      最近更新 更多