【问题标题】:Julia transpose grouped data Passing Tuple of column selectorsJulia转置分组数据传递列选择器的元组
【发布时间】:2022-10-01 19:39:37
【问题描述】:
ds = Dataset([[1, 1, 1, 2, 2, 2],
                        [\"foo\", \"bar\", \"monty\", \"foo\", \"bar\", \"monty\"],
                        [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"],
                        [1, 2, 3, 4, 5, 6]], [:g, :key, :foo, :bar])

在 InmemoryDatasets 中,转置函数可以传递列选择器的元组。

transpose(groupby(ds, :g), (:foo, :bar), id = :key)
Result:

g   foo bar monty   foo_1   bar_1   monty_1
identity    identity    identity    identity    identity    identity    identity
Int64?  String? String? String? Int64?  Int64?  Int64?
1   1   a   b   c   1   2   3
2   2   d   e   f   4   5   6

问题:

如何在 DataFrames.jl 中执行此操作?

如何在 R 和 Python 中做到这一点?

    标签: python r julia dataframes.jl


    【解决方案1】:

    R 中,pivot_wider 可用于整形。

    library(tidyr)
    pivot_wider(ds, names_from = key, values_from = c(foo, bar))
    

    -输出

    # A tibble: 2 × 7
          g foo_foo foo_bar foo_monty bar_foo bar_bar bar_monty
      <dbl> <chr>   <chr>   <chr>       <int>   <int>     <int>
    1     1 a       b       c               1       2         3
    2     2 d       e       f               4       5         6
    

    如果我们想获得相同的列名,我们可以rename这些列

    library(dplyr)
    library(stringr)
     ds %>% 
      rename("grp"= 'foo', '1' = 'bar') %>% 
      pivot_wider(names_from = key, values_from = c("grp", `1`), 
          names_glue = "{key}_{.value}") %>% 
      rename_with(~ str_remove(.x, "_grp"), ends_with('_grp'))
    

    -输出

    # A tibble: 2 × 7
          g foo   bar   monty foo_1 bar_1 monty_1
      <dbl> <chr> <chr> <chr> <int> <int>   <int>
    1     1 a     b     c         1     2       3
    2     2 d     e     f         4     5       6
    

    数据

    ds <- structure(list(g = c(1, 1, 1, 2, 2, 2), key = c("foo", "bar", 
    "monty", "foo", "bar", "monty"), foo = c("a", "b", "c", "d", 
    "e", "f"), bar = 1:6), class = "data.frame", row.names = c(NA, 
    -6L))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多