【问题标题】:How to create a new dataframe from existing dataframes?如何从现有数据框创建新数据框?
【发布时间】:2018-06-07 23:54:56
【问题描述】:

我有以下 2 个数据框:

df1

product_ID         tags
100         chocolate, sprinkles
101         chocolate, filled
102         glazed

df2

customer   product_ID
A            100
A            101
B            101
C            100
C            102
B            101
A            100
C            102

我应该能够像这样创建一个新的数据框。

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

其中单元格的内容表示产品属性的出现次数。

我用过merge,得到如下结果

df3 = pd.merge(df2, df1)
df3.drop(['product'], axis = 1)

customer       tags
A        chocolate, sprinkles
C        chocolate, sprinkles
A        chocolate, sprinkles
A        chocolate, filled
B        chocolate, filled
B        chocolate, filled
C        glazed
C        glazed

我们如何从这里得到最终结果? 提前致谢!

【问题讨论】:

    标签: python python-2.7 pandas dataframe


    【解决方案1】:

    使用get_dummies

    df.set_index('customer').tags.str.get_dummies(sep=',').sum(level=0)
    Out[593]: 
              chocolate  filled  glazed  sprinkles
    customer                                      
    A                 3       1       0          2
    C                 1       0       2          1
    B                 2       2       0          0
    

    【讨论】:

      【解决方案2】:

      您可以分两步完成:

      1. 使用一系列逗号分隔的字符串扩展/展平您的数据框。
      2. 使用pandas.crosstab 将您的计数制成表格。

      这是一个假设您已执行合并并且结果为 df 的示例:

      import numpy as np
      from itertools import chain
      
      # split by comma to form series of lists
      tag_split = df['tags'].str.split(',')
      
      # create expanded dataframe
      df_full = pd.DataFrame({'customer': np.repeat(df['customer'], tag_split.map(len)),
                              'tags': list(chain.from_iterable(tag_split))})
      
      # use pd.crosstab for result
      res = pd.crosstab(df_full['customer'], df_full['tags'])
      
      print(res)
      
      tags       filled   sprinkles  chocolate  glazed
      customer                                        
      A               1           2          3       0
      B               2           0          2       0
      C               0           1          1       2
      

      【讨论】:

      • 工作就像一个魅力!您能解释一下您在#create expand dataframes 部分下完成的代码吗?
      • 当然,np.repeat(df['customer'], tag_split.map(len)) 按相应的标签长度​​重复customer 列中的每个值。 list(chain.from_iterable(tag_split))tags 中创建一个包含所有逗号分隔元素的列表。您可以阅读 np.repeatitertools.chain.from_iterable 的文档。
      猜你喜欢
      • 2021-09-08
      • 2016-10-14
      • 2022-01-18
      • 2023-01-30
      • 1970-01-01
      • 2020-02-29
      • 2021-06-10
      相关资源
      最近更新 更多