【问题标题】:pandas groupby and create new columnspandas groupby 并创建新列
【发布时间】:2021-10-09 14:05:48
【问题描述】:

我的数据框如下所示:

user_id article_id  set_tags
1            31       true
1            32       false
1            35       false
2            11       false
2            11       true
3            56       true

我想得到这样的结果:

user_id total_articles  set_tags_true   set_tags_false
   1      3                    1               2
   2      2                    1               1
   3      1                    1               0

我是新手,我该怎么做? 我尝试使用 groupby.count(),但它似乎不正确。

【问题讨论】:

  • user_id 2 的 total_articles 列应该是 2 还是 1?
  • @PhilipEgger 我的错,应该是 2

标签: python pandas group-by count pandas-groupby


【解决方案1】:
import pandas as pd
df = pd.DataFrame(
    data = [[1,31,True],[1,32,False],[1,35,False],[2,11,False],[2,11,True],[3,56,True]],
    columns=['user_id','article_id','set_tags']
)
df
   user_id  article_id  set_tags
0        1          31      True
1        1          32     False
2        1          35     False
3        2          11     False
4        2          11      True
5        3          56      True

output_df = df.groupby('user_id').agg({'article_id':'nunique', 'set_tags':['sum', (lambda x:sum(~x))]})
output_df.columns = ['total_articles','set_tags_True','set_tags_False']
output_df
         total_articles  set_tags_True  set_tags_False
user_id                                               
1                     3              1               2
2                     1              1               1
3                     1              1               0

如果您希望 user_id 2 的 total_articles 条目为 2 而不是 1,只需将 nunique 替换为 count。

【讨论】:

  • 哎呀我这里有个问题,你能解释一下为什么会这样吗?如果我像这样完成数据帧:`df = pd.DataFrame(data = [['1','10001963',True],['2','40014',True],['2','40017', False],['1','40057',True]], columns=['user_id','article_id','set_tags'] ) ` 作为 set_tags_False 的结果,我得到:False True
猜你喜欢
  • 2021-05-16
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
  • 2019-12-22
  • 1970-01-01
  • 2020-02-05
相关资源
最近更新 更多