【问题标题】:Combining and Reshaping rows and columns of 2 dataframes in R or Python在 R 或 Python 中组合和重塑 2 个数据帧的行和列
【发布时间】:2018-12-13 17:06:47
【问题描述】:

有两个表 - 表 A 和表 B:

表 A:产品属性 该表包含两列;第一个是由整数表示的唯一产品 ID,第二个是包含分配给该产品的属性集合的字符串。

|---------------------|-----------------------|
|      product        |       tags            |
|---------------------|-----------------------|
|          100        | chocolate, sprinkles  |
|---------------------|-----------------------|
|          101        | chocolate, filled     |
|---------------------|-----------------------|
|          102        | glazed                |
|---------------------|-----------------------|

表 B:客户属性 第二个表也包含两列;第一个是包含客户名称的字符串,第二个是包含产品编号的整数。第二列的产品 ID 与表 A 第一列的产品 ID 相同。

customer    product
A           100
A           101
B           101
C           100
C           102
B           101
A           100
C           102

要求您创建一个匹配此格式的表格,其中单元格的内容代表客户产品属性的出现次数。

customer    chocolate   sprinkles   filled  glazed
A               ?           ?         ?        ?
B               ?           ?         ?        ?
C               ?           ?         ?        ?

谁能帮我用 R 或 Python 解决这个问题?

【问题讨论】:

  • 您能否在您的帖子中添加一些示例数据?
  • 您能否将您在 R 或 Python 中尝试的代码添加到您的帖子中?

标签: python r pandas dataframe reshape


【解决方案1】:

我们通过'product'列加入,在分隔符处拆分'tags'以扩展行,得到'tags','customer'与countspread它的频率为'wide'格式

library(tidyverse)
df1 %>% 
   right_join(df2) %>% 
   separate_rows(tags) %>%
   count(tags, customer) %>% 
   spread(tags, n, fill = 0)
# A tibble: 3 x 5
#  customer chocolate filled glazed sprinkles
#  <chr>        <dbl>  <dbl>  <dbl>     <dbl>
#1 A                3      1      0         2
#2 B                2      2      0         0
#3 C                1      0      2         1

数据

df1 <- structure(list(product = 100:102, tags = c("chocolate, sprinkles", 
"chocolate, filled", "glazed")), class = "data.frame", row.names = c(NA, 
 -3L))

df2 <- structure(list(customer = c("A", "A", "B", "C", "C", "B", "A", 
 "C"), product = c(100L, 101L, 101L, 100L, 102L, 101L, 100L, 102L
 )), class = "data.frame", row.names = c(NA, -8L))

【讨论】:

    【解决方案2】:

    python 方法可以大大简化,使用内置方法来获取虚拟变量。然后merge 后跟groupby+sum。从@SuryaMurali 提供的数据开始

    import pandas as pd
    
    df_A = pd.concat([df_A, df_A.tags.str.get_dummies(sep=', ')], 1).drop(columns='tags')
    df_B.merge(df_A).drop(columns='product').groupby('customer').sum()
    

    输出:

               filled   sprinkles  chocolate  glazed
    customer                                        
    A               1           2          3       0
    B               2           0          2       0
    C               0           1          1       2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-26
      • 1970-01-01
      • 1970-01-01
      • 2011-12-22
      • 1970-01-01
      • 2015-04-26
      • 1970-01-01
      相关资源
      最近更新 更多