数据框中的列式对应值

时间:2017-12-04 09:54:06

标签: python r data-science

给定一个数据帧,以Age为基础,我需要从其他列(运动,模式)获取对应值。有人可以帮助R / python代码吗?

test data set

事实上,如果我可以获得15岁,2岁的棒球比赛,那将会很有帮助;年龄19岁1高尔夫球和1场比赛。


输出应如下所示,以Age为基础变量
enter image description here

此外,使用Sport作为基础变量,模式应该有类似的摘要。谢谢

1 个答案:

答案 0 :(得分:2)

df = data.frame(Age = c(15,15,16,17,18,18,19,20),
                Sport = c("Baseball","Baseball","Baseball","Baseball","Baseball","Golf","Golf","Golf"),
                Mode = c("Play","Play","Play","Watch","Watch","Play","Play","Watch"),
                stringsAsFactors = F)

library(dplyr)
library(tidyr)

df %>%
  count(Age, Sport) %>%
  spread(Sport, n, fill = 0)

# # A tibble: 6 x 3
#     Age Baseball  Golf
# * <dbl>    <dbl> <dbl>
# 1    15        2     0
# 2    16        1     0
# 3    17        1     0
# 4    18        1     1
# 5    19        0     1
# 6    20        0     1


df %>%
  count(Age, Mode) %>%
  spread(Mode, n, fill = 0)

# # A tibble: 6 x 3
#     Age  Play Watch
# * <dbl> <dbl> <dbl>
# 1    15     2     0
# 2    16     1     0
# 3    17     0     1
# 4    18     1     1
# 5    19     1     0
# 6    20     0     1

如果您想生成单个输出,可以使用:

df = data.frame(Age = c(15,15,16,17,18,18,19,20),
                Sport = c("Baseball","Baseball","Baseball","Baseball","Baseball","Golf","Golf","Golf"),
                Mode = c("Play","Play","Play","Watch","Watch","Play","Play","Watch"),
                stringsAsFactors = F)

library(dplyr)
library(tidyr)
library(purrr)

# function that reshapes data based on a column name
# (uses Age column as an identifier/key)
f = function(x) {
df %>%
  group_by_("Age",x) %>%
  summarise(n = n()) %>%
  spread_(x, "n", fill = 0) %>%
  ungroup()
}


names(df)[names(df) != "Age"] %>%   # get all column names (different than Age)
  map(f) %>%                        # apply function to each column name
  reduce(left_join, by="Age")       # join datasets sequentially

# # A tibble: 6 x 5
#     Age Baseball  Golf  Play Watch
#   <dbl>    <dbl> <dbl> <dbl> <dbl>
# 1    15        2     0     2     0
# 2    16        1     0     1     0
# 3    17        1     0     0     1
# 4    18        1     1     1     1
# 5    19        0     1     1     0
# 6    20        0     1     0     1