【问题标题】:how to change the index value of numpy array with column values of pandas dataframe如何用熊猫数据框的列值更改numpy数组的索引值
【发布时间】:2020-05-24 21:22:05
【问题描述】:

我有一个数据框: 数据:

  user_id   item_id rating
0    772       36    3
1    471      228    5
2    641      401    4
3    312       98    4
4     58      504    5

我创建了一个随机数数组,其大小等于 item_id 中的唯一值

a = np.random.random(1662)

现在我想将数组的索引值转换为 item_id 的列值。如何更改数组的索引。 Item_id 总共有 1662 个值,但它不像 1 到 1662 那样继续。缺少一些值。最大值为 1681。所以我需要创建一个大小为 1662 的随机数组(即等于 item_id 的唯一值)。但是,如果我想查看与索引 (1677) 关联的随机值,我该如何查看呢?

由于数组的大小为 1662,因此索引的最大索引值为 1661。 所以我想将 1662 数字与 item_id 的值相关联

【问题讨论】:

  • 问题不清楚。可能是一个示例,有助于了解您到底想要实现什么。此外,在 pandas 中,您可以使用data.set_index('item_id') 将列设置为 index_column
  • @dumbPy 我想用列 item_id 设置 numpy 数组 a 的索引。
  • 您不能为 numpy 数组设置索引。在这种情况下,您可以为 pandas 数据框设置索引或使用 dict。如果要为 item_id 列中的每个唯一项设置一个随机数,可以使用字典作为item_id2num = { _id:random.randint(0, <some_upper_limit>) for _id in data.item_id }

标签: python pandas numpy indexing


【解决方案1】:

您的问题似乎含糊不清。

您在 item_id 中有一个包含 1662 个唯一值的随机数组 - 这意味着它可能存在于 item_id 中的值,也可能不存在。如果是这样,您想根据值重新索引 numpy 数组 a - 所以如果数字 36 在 'a' 和 'item_id' 中,你想要 a[36] = 36?

请澄清。

如果这是您想要的,那么只需像这样创建每个 item_id 的有序列表:

a = np.arrange(max(data.item_id))
b = np.isin(a, data.item_id)
a[b] = np.full(a[b], data.item_id)

更新:对于 a[36] = 随机数

a[b] = np.full(a[b], np.random.normal())

建议: 您还可以在数据框中添加随机数:

data['random'] = np.random.random(data.count())
# create a dict for indexing
random_dict = dict(zip(data['item_id'].tolist(), data['random'].tolist()))
# or set item_id as index:
data.index = data['item_id'].values

如果这有帮助,请告诉我!

【讨论】:

  • 我不想要 a[36] = 36。我想要如果项目 id 中存在 36,那么数组 a 中应该存在具有该索引的随机数,即 a[36] = 随机数跨度>
  • 这给了我一个错误,因为 ValueError: sequence too large;不能大于 32
猜你喜欢
  • 2020-04-01
  • 2017-03-18
  • 1970-01-01
  • 2018-02-20
  • 2017-09-17
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多