gpt4 book ai didi

r - 如何在 R 中为大型数据框使用字典?

转载 作者:行者123 更新时间:2023-12-04 00:54:00 25 4
gpt4 key购买 nike

我阅读了有关在 r 中创建字典的答案。

equivalent of a python dict in R

Is there a dictionary functionality in R

我有一个问题:如何在大型数据集中使用它?数据结构是这样的:

enter image description here

子样本的输入是:

structure(list(...1 = c("category 1", NA, NA, NA, "total", "category 2", 
NA, NA, NA, "total"), Items = c("product 1", "product 2", "product 3",
"product 4", NA, "product 1", "product 2", "product 3", "product 4",
NA), price = c(1, 2, 3, 4, 10, 3, 4, 5, 6, 18)), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))

我希望结果是这样的:

categoryx: {prodcut1:1, product2:2, product3:3....}

如果有 1000 个类别并且每个类别的产品数量不同,我该怎么办?上面两个链接中的答案,每个键的值应该手动添加,我不知道如何将它用于大型数据集。

或者有没有其他方法(除了创建字典)可以让我轻松提取每个类别的信息?

有人可以就这个问题给出想法吗?谢谢。

是否有可能在 python 中得到像字典(或字典列表)这样的结果?

例如 dict={category1: {prodcut1:1, product2:2, product3:3....}, category2: {prodcut1:3, product2:4, product3:5....} } } p>

所以我可以知道类别的索引并使用索引从字典中提取信息,也许它就像这样一个数据框:

            item      price

categoryx product1 2
product2 3

所以我可以针对特定类别进行操作?

最佳答案

hashmap 字典列表:

dat <-
structure(
list(
...1 = c("category 1", NA, NA, NA, "total", "category 2",
NA, NA, NA, "total"),
Items = c(
"product 1",
"product 2",
"product 3",
"product 4",
NA,
"product 1",
"product 2",
"product 3",
"product 4",
NA
),
price = c(1, 2, 3, 4, 10, 3, 4, 5, 6, 18)
),
row.names = c(NA,-10L),
class = c("tbl_df", "tbl", "data.frame")
)

library(hashmap)

dat_clean <- tidyr::fill(dat[!is.na(dat[["Items"]]), ], 1)

list_of_dicts <- lapply(split(dat_clean, dat_clean[[1]]), function(d){
hashmap(d[["Items"]], d[["price"]])
})

list_of_dicts
# $`category 1`
# ## (character) => (numeric)
# ## [product 1] => [+1.000000]
# ## [product 3] => [+3.000000]
# ## [product 4] => [+4.000000]
# ## [product 2] => [+2.000000]
#
# $`category 2`
# ## (character) => (numeric)
# ## [product 1] => [+3.000000]
# ## [product 3] => [+5.000000]
# ## [product 4] => [+6.000000]
# ## [product 2] => [+4.000000]


# get totals:
lapply(list_of_dicts, function(dict){
sum(dict$values())
})
# $`category 1`
# [1] 10
#
# $`category 2`
# [1] 18

关于r - 如何在 R 中为大型数据框使用字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64111179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com