【问题标题】:Pandas group coma separated words with second column then groupby and sumPandas 用第二列将逗号分隔的单词分组,然后分组并求和
【发布时间】:2019-09-20 18:51:11
【问题描述】:

我有一个包含 2 列的 pandas 数据框。 report_tags 是逗号分隔的单词,t_f 是表示是或否(1 或 0)的标志。我想用t_f 分隔这些逗号分隔的单词和分组。然后在名为count 的新列中汇总tag/t_f 分组

df 
    report_tags             t_f
0   bec,eac,fbi,ic3,scam    1
1   dlink,router,wifi       0
2   adobe                   0
3   bec, fbi                1
4   bec, fbi, scam          0

期望的输出:

df2
   tag    t_f   count
0  bec    1     2
1  eac    1     1
2  fbi    1     2
3  ic3    1     1
4  scam   1     1
5  dlink  0     1
6  router 0     1
7  wifi   0     1
8  adobe  0     1
9  bec    0     1
10 fbi    0     1
11 scam   0     1

【问题讨论】:

  • 使用df.explode,其余的应该遵循

标签: python pandas


【解决方案1】:

使用str.split + explode


k = dict(sort=False)

(df.set_index('t_f')['report_tags']
  .str.split(r',\s*').explode()
  .groupby(level=0, **k).value_counts(**k)
  .rename('count').reset_index())

    t_f report_tags  count
0     1         bec      2
1     1         eac      1
2     1         fbi      2
3     1         ic3      1
4     1        scam      1
5     0       adobe      1
6     0         bec      1
7     0       dlink      1
8     0         fbi      1
9     0      router      1
10    0        scam      1
11    0        wifi      1

【讨论】:

  • 我喜欢这个,但不断收到错误:AttributeError: 'Series' object has no attribute 'explode'。它指出的这一行是.str.split(r',\s*').explode()@user3483203
  • @sectechguy:你需要更新到 pandas 0.25+ 才能拥有explode
猜你喜欢
  • 2019-06-10
  • 1970-01-01
  • 2014-03-31
  • 2022-12-10
  • 1970-01-01
  • 1970-01-01
  • 2018-08-07
  • 1970-01-01
  • 2023-03-28
相关资源
最近更新 更多