【问题标题】:Python/R : If 2 columns have same value in multiple rows, add the values in the 3rd column and average the 4th, 5th and 6th columnPython/R :如果 2 列在多行中具有相同的值,则将第 3 列中的值相加并平均第 4、第 5 和第 6 列
【发布时间】:2015-09-07 15:11:17
【问题描述】:

输入:

0 77 1 2 3 5
0 78 2 4 6 1
0 78 1 2 3 5
3 79 0 4 5 2
3 79 6 8 2 1
3 79 1 2 3 1

输出:(将相同行的第 3 列值相加,并取第 4、5 和 6 列中所有值的平均值)

0 77 1.0 2.0 3.0 5.0
0 78 3.0 3.0 4.5 3.0
3 79 7.0 4.6 3.3 1.3

【问题讨论】:

  • 问题是什么?

标签: python r sorting dataframe findandmodify


【解决方案1】:

我们可以在R 中使用dplyr。我们按前两列分组,mutate 第 3 列 ('V3') 作为该列的 sum,并使用 summarise_each 得到列 3:6 的 mean

library(dplyr)
res <- df1 %>%
         group_by(V1, V2) %>% 
         mutate(V3=sum(V3))  %>% 
         summarise_each(funs(round(mean(.),1)), V3:V6)
as.data.frame(res)
#  V1 V2 V3  V4  V5  V6
#1  0 77  1 2.0 3.0 5.0
#2  0 78  3 3.0 4.5 3.0
#3  3 79  7 4.7 3.3 1.3

数据

df1 <- structure(list(V1 = c(0L, 0L, 0L, 3L, 3L, 3L), V2 = c(77L, 78L, 
78L, 79L, 79L, 79L), V3 = c(1L, 2L, 1L, 0L, 6L, 1L), V4 = c(2L, 
4L, 2L, 4L, 8L, 2L), V5 = c(3L, 6L, 3L, 5L, 2L, 3L), V6 = c(5L, 
1L, 5L, 2L, 1L, 1L)), .Names = c("V1", "V2", "V3", "V4", "V5", 
"V6"), class = "data.frame", row.names = c(NA, -6L))

【讨论】:

  • 非常感谢!这对我有用,虽然我不确定为什么我的问题收到 (-1)..
  • 我不能投票,因为我没有足够的声誉来投票,但再次感谢。
猜你喜欢
  • 1970-01-01
  • 2019-09-12
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
  • 2018-07-22
  • 2018-06-13
  • 2013-03-03
相关资源
最近更新 更多