简体   繁体   English

如何使用pandas数据框的列值更改numpy数组的索引值

[英]how to change the index value of numpy array with column values of pandas dataframe

I have a dataframe: data:我有一个数据框:数据:

  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

I have created a array of random number, whose size equal to unique values in item_id我创建了一个随机数数组,其大小等于 item_id 中的唯一值

a = np.random.random(1662)

Now I want to convert index value of array as column value of item_id.现在我想将数组的索引值转换为 item_id 的列值。 How to change index of array.如何更改数组的索引。 Item_id has total 1662 value but it is not continues like 1 to 1662. there are some values missing. Item_id 总共有 1662 个值,但它不像 1 到 1662 那样继续。缺少一些值。 the maximum value being 1681. So what I need is to create a random array of size 1662(ie equal to unique values of item_id).最大值是 1681。所以我需要创建一个大小为 1662(即等于 item_id 的唯一值)的随机数组。 But if i want to see random value associated with a index (1677) how can i see that?但是,如果我想查看与索引 (1677) 关联的随机值,我怎么能看到呢?

Since size of array is 1662 so the maximum index value is 1661 for index.由于数组的大小为 1662,因此索引的最大索引值为 1661。 so i want to associate 1662 number with the values of item_id所以我想将 1662 编号与 item_id 的值相关联

Your question seems vague.你的问题似乎很模糊。

You have a random array with 1662 unique values in item_id - meaning that its possible a value exists in item_id and its also possible that it doesn't.您在 item_id 中有一个包含 1662 个唯一值的随机数组 - 这意味着 item_id 中可能存在一个值,也可能不存在。 If it does, you want to re-index the numpy array a according to the value - so if the number 36 is in 'a' and in 'item_id' you want a[36] = 36?如果是这样,您想根据值重新索引 numpy 数组 a - 所以如果数字 36 在 'a' 和 'item_id' 中,您想要 a[36] = 36?

Please clarify.请说清楚。

If that's what you want, then simply create an ordered list of every item_id like so:如果这就是您想要的,那么只需像这样创建每个 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)

UPDATE: For a[36] = random-number更新:对于 a[36] = 随机数

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

Suggestion : You can also add random numbers inside your dataframe as:建议:您还可以在数据框中添加随机数,如下所示:

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

Let me know if this helps!让我知道这是否有帮助!

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

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