【问题标题】:How to convert multiple columns of date data into one column and group by another attribute?如何将多列日期数据转换为一列并按另一个属性分组?
【发布时间】:2020-04-28 16:28:17
【问题描述】:

我有一个包含所有国家/地区的数据集,以及多个日期列,其中包含被确认患有疾病的人数。像这样

country     1/1   1/2   1/3  1/4 .......   1/31
   A         2     4     0    5             10
   B         3     3     5    1             2
   C         4     2     6    8             3

enter image description here

我怎样才能把它变成这样:

enter image description here

 country    date     number of confirmed
   A        1/1              2
   A        1/2              4
   A        1/3              0
   A        1/4              5
   ..........................
   C        1/31             3

使用 R 工作室或 Python。用Excel手动改这个真的很难,但是我不知道怎么用python或者R来实现。

【问题讨论】:

标签: python r row


【解决方案1】:

在 R 中,您可以使用来自 dplyrpivot_longer

library(readr)
df <- read_table("
country     1/1   1/2   1/3  1/4
A           2     4     0    5
B           3     3     5    1
C           4     2     6    8"
)


library(dplyr)
df %>% 
  pivot_longer(cols = -country, names_to = "date", values_to = "no of confirmed")
# A tibble: 12 x 3
   country date  `no of confirmed`
   <chr>   <chr>             <dbl>
 1 A       1/1                   2
 2 A       1/2                   4
 3 A       1/3                   0
 4 A       1/4                   5
 5 B       1/1                   3
 6 B       1/2                   3
 7 B       1/3                   5
 8 B       1/4                   1
 9 C       1/1                   4
10 C       1/2                   2
11 C       1/3                   6
12 C       1/4                   8

【讨论】:

    【解决方案2】:

    您可以将数据集加载到 pandas DataFrame 中并使用 pandas 的数据透视函数 see here (Python)

    【讨论】:

      猜你喜欢
      • 2021-08-26
      • 2021-10-23
      • 2015-05-17
      • 1970-01-01
      • 2012-10-22
      • 2017-11-17
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      相关资源
      最近更新 更多