【问题标题】:Filtering while summarizing in python在python中汇总时过滤
【发布时间】:2019-03-14 01:33:07
【问题描述】:

我是一名 R 用户,目前正在学习 python。

通常,我使用 dplyr 对数据进行分组和汇总。例如,

data1 %>%
   dplyr::group_by(city) %>%
   dplyr::summarize(unique_customers = n_distinct(user_id, na.rm = TRUE),
                 converted_customers = n_distinct(user_id[type == "CONVERTED"], na.rm = TRUE)) %>%
   data.frame()

我已经能够实现 group_by 和 unique_customers,但是在 python 中放置条件 type == "CONVERTED" 时遇到了一些麻烦。我该怎么做?

编辑: 我现在的python代码:

data1.fillna(method = "ffill").groupby("city").agg({"user_id": "nunique"})

【问题讨论】:

  • apply(lambda x: (x=='CONVERTED')) ::: 类似于你想要在 R 中实现的目标
  • 我正在使用以下代码获取每个城市的唯一客户数量:data1.fillna(method = "ffill").groupby("city").agg({"user_id": "nunique "}) 但我想从另一列“类型”应用过滤器,它应该被过滤为仅转换,类似于 sql 中的语句时的情况。这就是我卡住的地方。 @roganjosh
  • 熊猫或纯python都可以。
  • 我只找到了“pandas-groupby”标签。希望这行得通。
  • 我已经为你添加了熊猫标签

标签: python r pandas dplyr pandas-groupby


【解决方案1】:
data1[data1.type=='CONVERTED'].fillna(method = "ffill").groupby("city").agg({"user_id": "nunique"})

【讨论】:

  • 嘿,感谢您的回答@Mysterious 我认为这只会给converted_customers,对吗?我需要 unique_customers 和 converted_customers。
【解决方案2】:

使用datar 将您的 R 代码翻译成 python 很容易:

from datar.all import f, group_by, summarize, n_distinct

data1 >> \
   group_by(f.city) >> \
   summarize(
      unique_customers=n_distinct(f.user_id, na_rm=True),
      converted_customers=n_distinct(f.user_id[f.type == "CONVERTED"], na_rm=True)
   )

免责声明:我是datar 包的作者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多